Matteo Pagliazzi
Matteo Pagliazzi

Reputation: 5260

using new in function prototype's property

I've seen a Javascript project where a prototype property is defined like this:

myFunc.prototype.a = new myObject()

I'm wondering what happens when I call new myFunc() to the a property:

Does it return the result of new myObject() or everytime I call myFunc.a it calls new myObject()?

And on different myFunc instances the a property is the same one as it happens for normal prototype properties or every instance's a is different myObject() instance?

See this http://backbonejs.org/docs/todos.html: every TodoList instance will share the same localStorage, so the same Backbone.LocalStorage() instance?

Upvotes: 2

Views: 50

Answers (2)

LetterEh
LetterEh

Reputation: 26696

Hopefully, this will help you out:

var Person = function (name, age) {
    this.getName = function () { return name; };
    this.getAge  = function () { return age; };
};


var Employee = function (employee_id) {
    this.printBadge = function () {
        console.log("#" + employee_id + " | " + this.record.getName());
    };
};

Employee.prototype.record = new Person("Bob", 32);

var jim  = new Employee(1),
    doug = new Employee(2);

jim.printBadge(); //  #1 | Bob
doug.printBadge(); // #2 | Bob

The "prefer composition to inheritance" mantra goes quadruple for JavaScript.
You can quite happily override a particular object on a person:

jim.record = { getName : function () { return "Jim"; } };
jim.printBadge();  // #1 | Jim
doug.printBadge(); // #2 | Bob

Just be careful when modifying properties of the prototype object (the object which instances refer to).

var jeff = new Employee(3);
jeff.record.getName = function () { return "OMG! Yuse guys is scr00d!" };

jim.printBadge();  // #1 | Jim
doug.printBadge(); // #2 | OMG! Yuse guys is scr00d!
jeff.printBadge(); // #3 | OMG! Yuse guys is scr00d!

Reason being that you changed a property of the shared, prototype object (static, in other languages), rather than replacing the WHOLE prototype object (referencing a new object, instead of the static object) like in Jim's case.

But the X.prototype.y = new Z(); can be seen like this, simply:

var bob = new Person("Bob", 32);
Employee.prototype.record = bob;

var jim  = new Employee(1),
    doug = new Employee(2),
    jeff = new Employee(3);

Upvotes: 1

xavierm02
xavierm02

Reputation: 8767

No, all your instances of myObject will have the same __proto__.

If you access a from an object, you'll access the one of the prototype but if you set a on one object, then this object will have whatever a you gave him while the others will keep the old one.

Upvotes: 3

Related Questions