当我声明一个新的对象类型时:
var MyType = function(constructorArg) {
this.whatever = constructorArg;
};
var myTypeInstance = new MyType('hehe');
在这种情况下,this
指的是分配给MyType
的功能。
现在让我们为属性whatever
添加一个简单的访问器(不使用原型):
var MyType = function(constructorArg) {
this.whatever = constructorArg;
this.getWhatever = function() {
// Here this should logically point to the function assigned
// to this.whatever instead of the current instance of MyType.
return this.whatever;
};
};
这适用吗?
但是为什么this
不是在分配给属性whatever
的函数体内,而不是指向该函数本身?
感谢您的帮助!
EDIT
:我会修改我的例子:
var MyType = function(arg) {
this.property = arg;
this.MySubType = function(subTypeArg) {
this.subTypeProperty = subTypeArg;
// What is "this" refereing to here ?
// To the instance of MyType, or to the instance of MySubType ?
// I know it would not make sense to do something like this in real world
// but i'm trying to have a clearer understanding of the way "this" is set.
};
}
EDIT
:正如评论中所述:
使用时
myTypeInstance.MySubType('hehe');
然后这是指myTypeInstance。
使用时
var mySubTypeInstance = new myTypeInstance.MySubType('hehe');
然后这是指mySubTypeInstance
如果我理解得很好。
答案 0 :(得分:1)
关于您的修改,它总是如此:它取决于您调用this.MySubType
的 。
如果将其称为this.MySubType()
,即作为对象方法,则this
(在函数内部)将引用this
(函数外部),这是一个MyType
的实例。
如果您将其称为new this.MySubType()
,则会引用MySubType
的新实例。
如果您将其称为this.MySubType.call(foo)
,则this
会引用foo
。
查看MDN文档section "Function context"。
答案 1 :(得分:0)
我不认为这个在匿名函数中获得分配给它的新值。您可能需要look this page。
- 只能从外部函数中的语句访问内部函数。
- 内部函数形成一个闭包:内部函数可以使用外部函数的参数和变量,而外部函数不能使用内部函数的参数和变量。
我的猜测是这个必须可以从内部函数内部访问,因此不会被覆盖。
编辑:我在打字时没有看到评论,Felix Kling在评论中解释得更好。