Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

constructor - does javascript's this object refer to newly created object in the way i think

So, when we create constructor function for creating new object the new keyword does 3 things I'am going to explain it but please correct me if I'am wrong i want to be sure I'am correct

first i will create a constructor function

function ObjectCreate(){
    this.a = "a";
    this.b = "b";

    ObjectCreate.prototype.show = function(){
        alert(this.a+" "+this.b);
    }
}

obj1 = new ObjectCreate();

now the first thing new keyword does is create new object and set its secret link to its constructor's prototype and pass it to the constructor function where now the this can refer to it and please note this does not refer to obj1 at this point because once constructor finished creating object only then it returns the newly created object to obj1 variable. i ask this question because some people say that this refer to the obj1 object in this case. so am i right here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your phrasing is a bit confusing, but I'll do my best. First, you should note that your curly braces are a bit off. Your code should look like this:

function ObjectCreate(){
   this.a = "a";
   this.b = "b";
}

ObjectCreate.prototype.show = function(){
     alert(this.a+" "+this.b);
}

obj1 = new ObjectCreate();

You need to define your constructor, then attach things to its prototype.

When you call the constructor, the this keyword does basically refer to the new object being created. This is important because, for example, you could write a constructor like:

function ObjectCreate(x,y){
   this.a = x*x;
   this.b = y*x+4;
}
obj1 = new ObjectCreate(10,20);

Here, as in all constructors, this refers to the instance being created (obj1, in this case).

I think you suggested that this refers to the object's prototype, but that would make this.a and this.b static variables, which would be useless in a constructor like the one here, since every time you initialized a new object you would change the vale of this.a and this.b for all previously existing objects, and that just isn't useful.

I hope that answered your question. If not, please go ahead and leave comments for further clarification.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...