var name = "this is window"
var a = {
name:"this is a",
callname:function(){
alert(this.name)
}
}
function B(){
alert(this.name)//this is B
}
B.prototype.name = "this is B";
B.prototype.callname = function(){
alert(this.name)
}
B.callname = function(){
alert(this.name)
}
//a.callname()
//B.callname()
//(new B()).callname()
What are the values of the last three? ? ?
Before answering your question, let’s look at an example
Let’s break down your problem one by one (please use the Chrome browser’s developer tools to verify)
What does B.callname() output?
B is a function, its name="B", the B.callname method is called, and the caller is B, then this in the callname method refers to B. Do you remember what B.name is? Just look at the first example above to understand.
You will ask, why is "this is B" not defined by B.prototype.name? Because the properties defined in B's prototype can only be directly accessed by instances of B.
If you still don’t believe it, then please change all names, such as xname, and the answer to this question will become undefined
a.callname() What does it output?
a itself is an object instance, which is defined in JSON. The above code is equivalent to
The caller of callname is a, then this in callname is a
(new B()).callname() What does it output?
First,
new B()
is executed first, creating an anonymous instance. Let’s temporarily name it b, that is,b = new B()
, in function B This is referred to as b at this time, and then the method alert in the B function body is executed sequentially. What is b.name? b is an instance, it does not have a name attribute, so it will look for name in the prototype definition of the parent class, and find "this is B".new B()
先执行, 创建了一个匿名实例,我们暂且给他命名为b, 即b = new B()
, 函数B中的this此时被指代为 b, 然后才是依次执行B函数体内的方法alert, b.name是什么?b是个实例,它本身没有name属性, 就会去父类的prototype定义中找name,找到了 "this is B".然后,
b.callname()
Then,b.callname()
is executed, and callname is defined This refers to the method caller b. The instance b itself does not have a name attribute. It will find the name attribute value of the prototype in the parent class and return it.In the first one, this represents object a, so this is a pops up. In the second one, B represents function B, and the name of the function B pops up. In the third one, this is B pops up first, because when instantiating The function will be executed. Then there will be a syntax error because there is no semicolon in the statement before (new B()). If there is no syntax error, another this is B will pop up because the instance object calls the name attribute on the prototype object.