當我聲明一個新對象類型:JavaScript - 這是指什麼?
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
如果我理解良好。
*「在這種情況下,'this'指的是分配給'MyType'的函數。」*否!如果用'new'調用,'this'引用一個從MyType.prototype繼承的新對象。 ''這個** **從不**指代函數本身*除非你明確地調用函數(即'func.call(func)')。請查看[MDN關於'this'的文檔](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this),它很好地概述了它是如何實現的作品。 –
是的,對不起,這就是我的意思,它指的是實例。那麼accessor中的'this'是指什麼?它應該引用一個使用'var instance = new this.whatever();'創建的實例? – Virus721
無處。但是如果'this.whatever'是一個「子類型」而不是訪問器,那麼引用'this'應該指向那個子類型的實例,而不是'MyType'的實例? – Virus721