'this'关键字,不清楚 [英] 'this' keyword, not clear
问题描述
我对以下代码中的'此'关键字感到困惑,有两个'this':
I get confused about 'this' keyword in the following codes, there are two 'this':
var Foo = function(string){
this.name=string // 1st-this
}
Foo.prototype.get_name = function(){
return this.name // 2nd-this
}
var myFoo = new Foo('John')
the_name=myFoo.get_name()
' the_name '等于'John',原型方法获取返回 this.name 的名称。但有人可以向我解释第1个 - 这个和第2个这个,它们代表什么?
'the_name' is equal to 'John', the prototype method get the name by return this.name. But can anyone explain to me the 1st-this and 2nd-this, what do they stand for?
推荐答案
在Javascript中,这个
的值取决于你调用函数的方式。
In Javascript, the value of this
is dependent on the way you call the function.
有五种方法可以在JS中调用函数,它们都对有影响
:
There are 5 ways to call a function in JS, and they all have effect on this
:
-
new Foo();
< =这里,你正在创建一个新对象,并且此
将反映该新对象 -
Foo();
< =此处,你按原样调用函数,这个
将是全局对象(!) -
var obj = {foo:Foo};
< =这里,你将函数作为
obj.foo();的方法调用OBJ
;此
将obj
-
Foo.call (thisObject,arg1,arg2);
< =此处,您可以在第一个参数 $ b中指定 -
Foo.apply(thisObject,[args]);
< =这里,你可以指定这个$的值c $ c>在第一个参数中
此
的值$ b new Foo();
<= here, you’re creating a new object, andthis
will reflect that new objectFoo();
<= here, you're calling the function as-is, andthis
will be the global object(!)var obj = { foo: Foo };
<= here, you're calling the function as a method of
obj.foo();obj
;this
will beobj
Foo.call(thisObject, arg1, arg2);
<= here, you can specify the value ofthis
in the first argumentFoo.apply(thisObject, [args]);
<= here, you can specify the value ofthis
in the first argument
在4和5中,调用和 apply 是 call
,你需要分别传递所有参数,而使用 apply
,你可以传递一个包含所有参数的数组。
In 4 and 5, the difference between call and apply is that with call
, you need to pass all the arguments separately, whereas with apply
, you can pass an array containing all the arguments.
注意,在上面的例子2中,函数应该被称为 foo
而不是 Foo
。由于不可能知道是否应该使用 new
来调用函数,所以一致意见是如果它是构造函数则用大写字母启动函数名称(并应与 new
一起使用);否则,它应该以小写字母开头。
Note that in my example 2 above, the function should have been called foo
instead of Foo
. Since it’s impossible to know off-hand whether a function is supposed to be called with new
or not, the consensus is to start the function name with a capital letter if it’s a constructor (and should be used with new
); otherwise, it should start with lowercase.
这篇关于'this'关键字,不清楚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!