Reputation:
Suppose there is:
function someConstructor(){
// initialize
}
someConstructor.prop = {test:'test'};
var obj1 = new someConstructor();
var obj2 = new someConstructor();
My guess would be that there is still only one copy of prop
available via someConstructor.prop
for obj1
and obj2
available via someConstructor.
Upvotes: 0
Views: 64
Reputation: 664206
function SomeConstructor(){}; someConstructor.prop = …
JavaScript is case sensitive, this is example won't work.
My guess would be that there is still only one copy of prop for obj1 and obj2.
No. There won't be any copies at all. prop
is a property of the function object, and has nothing to do with obj1
or obj2
. It is not inherited by them.
And that's the difference to using a property on the prototype, which is the object from which obj1
and obj2
do inherit.
a static property that is copied directly to the object
Only if by "object" you mean the constructor function here. In JS, there are no classes, and no "static" properties. Yet, the correspondent of "static class attributes" would be properties on the constructor function.
Upvotes: 0
Reputation: 3402
Prototype is used to make sure that 1 and only 1 object is there for all instances. However those instances may override that prototype with their own objects. In firefox at least, setting Test.opts
does not allow o1
or o2
to inherit it. But setting Test.prototype.opts
does.
Try the following:
var Test = function () {};
Test.opts = {helo: "hello"};
var o1 = new Test();
var o2 = new Test();
console.log( o1.opts ); // undefined
o1.opts = {helo: "bye"};
console.log( o2.opts ); // undefined
Test.prototype.opts = {helo: "hello"};
console.log( o1.opts ); // Object { helo: "bye" }
console.log( o2.opts ); // Object { helo: "hello" }
Upvotes: 4