function Foo(name) { this.name = name; } Foo.prototype.myName = function () { return this.name; } var a = new Foo('a'); var b = new Foo('b'); a.myName(); // 'a' b.myName(); // 'b'
This piece of code shows 2 tips for "class-oriented"
function Foo() {/** .. */} Foo.prototype = { / * * .. * / } // Create a new prototype object var a1 = new Foo (); a1.constructor === Foo; // false a1.constructor ==== Object; // true
a1 does not have a .constructor property, so it will delegate Foo.prototype on the [[Prototype]] chain. But this object also has no .constructor property, so it will continue to delegate, this time it will delegate to Object.prototype at the top of the delegation chain. This object has a .constructor property that points to the built-in Object (...) function.
Of course, you can also manually add a .constructor property to Foo.prototype. .constructor is not an immutable property . So a1.constructor is actually not trusted. They do not necessarily point to the default function reference. a1.constructor is a very unreliable and unsafe reference. Generally speaking, try to avoid using these references