In JavaScript, this is defined when created. What does this sentence mean?
function Foo () {
this.name = ' Peter ';
}
Foo ();
Console.log (name);//this is the global object when it is created, so the name here is Peter;
So what's different about adding a keyword new?
Let's say varobj = new Foo ();
In JavaScript, the new keyword does three things:
First, generate a new object
One, Varo = {}; Generate an Empty object o
Second, o.__proto__= foo.prototype;//the prototype chain to pass to O
Third, Foo.call (o);/to pass the value of oneself
return o;
When
New Foo ();
Console.log (name); The name is not defined
What is the inheritance of prototype? See Nanyi's article
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F ();
Child.prototype.constructor = child;
Because the object is passed by reference, when I assign a value f.prototype= parent.prototype, then f.prototype.xx= ' sth '; This time the original Parent.prototype will be changed accordingly, so to use the empty object as an intermediary.
Plus our definition of new, we can get:
var F = function () {};
F.prototype = Parent.prototype;
var o = {};
o.__proto__ = F.prototype;
F.call (o);
Child.prototype = O;
Child.prototype.constructor = child;
Since we assign an object to Child.prototype, when we change the constructor attribute to the child, we change only one property of the object o, not an O prototype. So it has no effect on the original parent.
Don't believe it.
Give it a try.
Console.log (O.prototype = = = o.__proto__); False
The prototype chain is to find its own attributes first, then find prototype, and then continue to look up.
var o = {};
var k = {
Call:function () {
Console.log (' a Try ');
}
};
K.__proto__.call = function () {
Console.log (' second try ');
};
o.__proto__ = k;
O.call ();