You didn't know about JavaScript series (52)-.constructor

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"

1. This.name = name adds the .name attribute to each object. (This new binding rule)
2. Foo.prototype.myName adds a function to the Foo.prototype object. a.myName works because during the creation process, both a and b are associated with Foo.prototype. When a and b can not be found myName, it will pass found delegate Foo.prototype

 

a.constructor === Foo true means that a does indeed have a .constructor attribute pointing to Foo, but this is not the case. .constructor reference is also delegated to Foo.prototype, and Foo.prototype.constructor points to Foo by default

 

The .constructor property of Foo.prototype is just the default property of the Foo function when it is declared . If you create a new object and replace the function's default .prototype object reference, the new object will not automatically get the .constructor property
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

 

Guess you like

Origin www.cnblogs.com/wzndkj/p/12702804.html
Recommended