0

In JavaScript, if I create a constructor function Foo, a prototype object will also be created as Foo.prototype. So I tried this:

function Foo() { this.xx = 1000}

I thought the created prototype object Foo.prototype will have the property xx = 1000. So I tried this:

console.log(Foo.prototype.xx);

But the result is "undefined". Why is this?

Shouldn't there be a Foo.prototype object with single property xx to be 1000?

Thanks.

istos
  • 2,654
  • 1
  • 17
  • 19
totally
  • 423
  • 1
  • 3
  • 11
  • 1
    `this.xx` refers to the instance object, not it's prototype... – Bhojendra Rauniyar Jan 25 '15 at 20:48
  • Whatever you do in the constructor, it will not be evaluated until you invoke the constructor. Without a `new Foo()`, there will be no `xx` anywhere. And it's not on the prototype either. – Bergi Jan 25 '15 at 22:05
  • maybe the following answer can help you: http://stackoverflow.com/a/16063711/1641941 – HMR Jan 26 '15 at 01:21

1 Answers1

0

If you add the property inside the constructor, each instance will have an own copy:

function Foo1() {
    this.xx = [1000];
}
var foo1 = new Foo1(),
    foo2 = new Foo1();
foo1.hasOwnProperty('xx'); // true
foo2.hasOwnProperty('xx'); // true
foo1.xx == foo2.xx;        // false (each instance has a different copy)

You can also use prototypical inheritance. Then, a the same inherited property is shared among all the instances:

function Foo2() {}
var foo1 = new Foo2(),
    foo2 = new Foo2();
'xx' in foo1; // false
'xx' in foo2; // false
Foo2.prototype.xx = [1000];
'xx' in foo1; // true
'xx' in foo2; // true
foo1.hasOwnProperty('xx'); // false (it's inherited)
foo2.hasOwnProperty('xx'); // false (it's inherited)
foo1.xx == foo2.xx;        // true (all instances share the same value)
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • Thanks oriol for the quick answer. So I guess property xx will always be the property in instantiated object (the object this point to, and not "shared" from Foo.prototype), and Foo.prototype will always be empty to start with ? – totally Jan 25 '15 at 21:42
  • @totally Yes. Well, `Foo.prototype` will contain a non-enumerable `constructor` property with the value `Foo`, and will also inherit from `Object.prototype`. – Oriol Jan 25 '15 at 22:18