function Mammal(name){
this.name = name;
}
Mammal.prototype.displayName = function(){
return this.name;
}
function Organism(name){
this.orgName = name;
}
Organism.prototype.print = function(){
return this.orgName;
}
Organism.prototype = new Mammal(); //Organism inherits Mammal
//Testing
var o = new Organism('Human');
o.print()
This comes as undefined. Why? this should show since it is a method of class Organism.
print() does not show up in the object
When you do:
Organism.prototype = new Mammal(); //Organism inherits Mammal
you replace the entire prototype object, thus wiping out the previously assigned:
Organism.prototype.print = function(){
return this.orgName;
}
You can fix it by changing the order so you "add" your new method to the inherited prototype:
function Organism(name){
this.orgName = name;
}
Organism.prototype = new Mammal(); //Organism inherits Mammal
Organism.prototype.print = function(){
return this.orgName;
}
FYI as an aside, you should be thinking about using Organism.prototype = Object.create(Mammal.prototype); instead and you should be calling the constructor of the base object too. See here on MDN for examples.
When you assign
Organism.prototype = new Mammal();
you are clobbering the Organism.prototype object that had the print function on it. Try this instead for your inheritance:
function Mammal(name){
this.name = name;
}
Mammal.prototype.displayName = function(){
return this.name;
}
function Organism(name){
this.orgName = name;
}
Organism.prototype = Object.create(Mammal.prototype);
Organism.constructor = Mammal;
// or _.extend(), if using underscore
jQuery.extend(Organism.prototype, {
print: function(){
return this.orgName;
}
});
//Testing
var o = new Organism('Human');
o.print()
Related
I have a class with a method
function MyClass(name){
this._name = name;
}
MyClass.prototype.test=function(){
console.log(this._name);
}
This work if create new instance
var a = new MyClass('demo');
a.test();
But, now I want call this class like a function without create instance
MyClass('demo2').test();
Is this possible?
You can check if this is an instance of the class, if the check is false it means that it is called as a function and you can return a new instance:
function MyClass(name){
if (!(this instanceof MyClass)) {
return new MyClass(name);
}
this._name = name;
}
in this way you can get a new instance of the class with or without the new keyword.
Yes it is possible. You can return a custom object with necessary properties.
function MyClass(name){
// private variable
var _name = name;
var getName = function(){
return _name;
};
// public properties
return {
test: getName
}
}
console.log(MyClass('Foo').test())
console.log(MyClass('Foo')._name)
or you can have inner private class which is only available inside MyClass.
function MyClass(name){
function Person(){
this._name = name;
}
Person.prototype.getName = function(){
return this._name
}
return new Person()
}
console.log(MyClass('Foo').getName())
console.log(MyClass('Foo')._name)
I have a Dog Constructor as follows:
var Dog = function(name,type)
{
this.name = name;
this.type = type;
this.normalObjFunc = function()
{
this.name = "kl";
}
var retfunc = function()
{
return this.name;
}
return retfunc;
}
In the retfunc function() , I am trying to access this.name in the following way.
var dogObj = new Dog("hj","labrador");
alert(dogObj());
In the output , I get as "result" in the alert messageBox, I am not getting what does the o/p "result" ,means?
I have purposely not included retfunc to "this" object, does it mean I cant access this.name inside retfunc() because a SEparate "this" would be created?
I am also aware of the fact that assigning var self =this solves the problem.
I just want to know what is "result" which is the output and why not undefined ideally?
The issue is because the scope of this within the functions will be the window. You need to cache the object reference in a variable and call that, like this:
var Dog = function(name, type) {
var _this = this;
this.name = name;
this.type = type;
this.normalObjFunc = function() {
_this.name = "kl";
}
var retfunc = function() {
return _this.name;
}
return retfunc;
}
var dogObj = new Dog("hj", "labrador");
console.log(dogObj());
Alternatively you can prototype the functions to keep the scope of this, however you would need to change your logic as it means that the return value of Dog() could not be the function.
var Dog = function(name, type) {
this.name = name;
this.type = type;
}
Dog.prototype.normalObjFunc = function() {
this.name = "kl";
}
Dog.prototype.retfunc = function() {
return this.name;
}
var dogObj = new Dog("hj", "labrador");
console.log(dogObj.retfunc());
What am I trying to do is as following:
var Person = function(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
}
// This will return error;
console.log(Person('John').getName());
// While this won't.
var p1 = new Person('john');
console.log(p1.getName());
Am I misunderstanding something?
// This will return error;
console.log(Person('John').getName());
it returns an error bcoz Person() by default returns undefined ,but if you use new it will return the newly created object.
// While this won't.
var p1 = new Person('john');
console.log(p1.getName());
this works bcoz a new object with __proto__ set to Person.prototype is returned and since there is a getName() on it , it works as expected.
you may use scope safe constructor for your constructor to work without explicit new.
function Person(name) {
if(this instanceof Person) {
this.name = name;
} else {
return new Person(name);
}
}
http://www.mikepackdev.com/blog_posts/9-new-scope-safe-constructors-in-oo-javascript
If you don't want to have the new keyword all over your code (and I can't think of a good reason to want that, you would be basically hiding an important information), you could just do something like:
var pPerson = function(name) {
this.name = name;
};
pPerson.prototype.getName = function () {
return this.name;
};
var Person = function (name) {
return new pPerson(name);
};
You can use Object.create() if you don't want to use the new keyword. Here's an example from MDN:
// Animal properties and method encapsulation
var Animal = {
type: "Invertebrates", // Default value of properties
displayType : function(){ // Method which will display type of Animal
console.log(this.type);
}
}
// Create new animal type called animal1
var animal1 = Object.create(Animal);
animal1.displayType(); // Output:Invertebrates
// Create new animal type called Fishes
var fish = Object.create(Animal);
fish.type = "Fishes";
fish.displayType(); // Output:Fishes
If you really really hate your self, you can do this
var Person = function(name) {
var This = {};
This.name = name;
//See note
Object.setPrototypeOf(This, arguments.callee.prototype);
return This;
}
Person.prototype.getName = function () {
return this.name;
}
var p = Person('John');
console.log(p.getName());
Note
You absolutely have to read about this.
You can try creating prototype functions as a part of parent function itself.
var Person = function(name) {
this.name = name;
this.get_name = function() {
return this.name;
}
return this;
}
Person.prototype.getName = function() {
return this.name;
}
// This will return error;
console.log(Person('John').get_name());
// While this won't.
var p1 = new Person('john');
console.log(p1.getName());
i am just starting learn a prototypes in javascript an i can't understand what a problem is in my code. I'm sorry, my question may seem silly
i got an error like this :
Uncaught TypeError: undefined is not a function
why is undefined? I inherited a function of the user.
can't understand it :(
var user = {
sayName: function() {
console.log(this.name)
}
};
user.name = "viktor";
user.sayName();
var user2 = {};
user2.prototype = user;
user2.name = "segey";
user2.sayName();
All you need to set up the prototype chain with plain objects is:
var user2 = Object.create(user); // set `user` as prototype of `user2`
user2.name = "segey";
user2.sayName();
For you question correct solution will:
function User() {
this.name = 'Viktor';
return this;
}
User.prototype = Object.create({
sayName: function() {
return this.name;
}
});
function User2() {}
User2.prototype = Object.create(User.prototype);
var user = new User();
user.sayName(); // 'Viktor'
user2 = new User2();
user2.name = 'Bogdan';
user2.sayName(); // 'Bogdan'
And detailed explanation with example.
Let say we have some basic class Animal. Our Animal have age and name.
function Animal() {
this.age = 5;
this.name = "Stuffy";
return this;
}
Animal.prototype = Object.create({
getAge: function() {
return this.age;
},
getName: function() {
return this.name;
}
});
And when I spent some time with architecture I understand that I also need SubClass of Animal. For example, let it will be Dog class with new property and functions. And also Dog must extend functions and properties from Animal class.
function Dog() {
Animal.apply(this, arguments); // Call parent constructor
this.wantsEat = true; // Add new properties
return this;
}
Dog.prototype = Object.create(Animal.prototype); // Create object with Animal prototype
Object.extend(Dog.prototype, { // Any extend() function, wish you want
constructor: Dog, // Restore constructor for Dog class
eat: function() {
this.wantsEat = false;
return this;
}
});
Or you can use Object.defineProperties() and extend in this way:
Dog.prototype = Object.create(Animal.prototype, {
constructor: {
value: Dog
},
eat: {
value: function() {
this.wantsEat = false;
return this;
}
}
});
Is it possible to define an object within another object? I'm thinking something like this:
function MyObj(name) {
this.name = name;
function EmbeddedObj(id) {
this.id = id;
}
}
And I could then create an EmbeddedObj like this:
var myEmbeddedObj = new MyObj.EmbeddedObj();
Meme for bonus points: Objectception! :o
Yes, and no.
function MyObj(name) {
this.name = name;
}
MyObj.EmbeddedObj = function EmbeddedObj(id) {
this.id = id;
}
new MyObj.EmbeddedObj(42);
Would run, but it might not yield the expected results for "embedded object" (see comment).
Note that in the case of new expr the expression is evaluated first so, in this case it creates a new object using the function-object evaluated from MyObject.EmbeddedObj as a constructor. (There is a silly rule with parenthesis in the expression, but that's another story.)
Now, if a "parent" and "child" relationship was desired, that could be done, using a more round-about method:
function Parent (name) {
this.name = name;
var parent = this; // for closure
this.Child = function Child () {
this.Parent = parent;
}
}
// create new parent object
var parent = new Parent();
// each new parent has a different Child constructor and
// any function-object can be used as a constructor
var child = new parent.Child();
// true: child is "bound" to parent
child.Parent === parent;
function MyObj(name) {
this.name = name;
}
MyObj.EmbeddedObj = function(id) {
this.id = id;
}
var myEmbeddedObj = new MyObj.EmbeddedObj();
Does that look like what you're after?
Here is example of nested constructor.
function cimdb(name,review,year) {
function nestedConstructor(name,review,year) {
this.name = name;
this.review = review;
this.year = year
};
this.name = name;
this[name] = new nestedConstructor(name,review,year);
}
var lionking = new cimdb("The Lion King", "The lion King review ..", 2015);
I guess this is what you mean by nested object constructor.
The easiest way to nest other objects in a constructor is to create its field and then create a new object when invoking the constructor. Below is an example:
function Product(name, price, category, producer) {
this.name = name;
this.price = price;
this.category = category;
// nested constructor
this.producer = producer;
}
function Producer(contributor, address) {
this.contributor = contributor;
this.address = address;
}
let prod1 = new Product("Milk", 2.5, "Dairy", new Producer("Nestle", "Warszawa"));