当我声明一个新的对象类型时:
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');
那么 this 指的是 myTypeInstance。
使用时
var mySubTypeInstance = new myTypeInstance.MySubType('hehe');
那么 this 指的是 mySubTypeInstance
如果我理解得很好。