JavaScript this refers to the meaning of new and prototype, the prototype chain __this

Source: Internet
Author: User

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 ();


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.