2013-07-29 28 views
0

當我聲明一個新對象類型: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

如果我理解良好。

+4

*「在這種情況下,'this'指的是分配給'MyType'的函數。」*否!如果用'new'調用,'this'引用一個從MyType.prototype繼承的新對象。 ''這個** **從不**指代函數本身*除非你明確地調用函數(即'func.call(func)')。請查看[MDN關於'this'的文檔](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this),它很好地概述了它是如何實現的作品。 –

+0

是的,對不起,這就是我的意思,它指的是實例。那麼accessor中的'this'是指什麼?它應該引用一個使用'var instance = new this.whatever();'創建的實例? – Virus721

+0

無處。但是如果'this.whatever'是一個「子類型」而不是訪問器,那麼引用'this'應該指向那個子類型的實例,而不是'MyType'的實例? – Virus721

回答

1

關於你的編輯,它就像它總是這樣:它取決於如何你叫this.MySubType

  • 如果您將它稱爲this.MySubType()即作爲對象方法,則this(函數內部)將參考this(函數外部),其是MyType的實例。

  • 如果您將它稱爲new this.MySubType()那麼它指的是MySubType的新實例。

  • 如果您將其稱爲this.MySubType.call(foo),this指的是foo

查看MDN文檔section "Function context"

0

我不認爲這個在匿名函數中得到一個賦予它的新值。您可能需要look this page

  • 內功能只能從外功能語句訪問。
  • 內部函數形成一個閉包:內部函數可以使用外部函數的參數和變量,而外部函數不能使用內部函數的參數和變量。

我的猜測是,這必須從內部函數內部,因此不會被覆蓋accessable。

編輯: Felix Kling在他的評論中解釋得很好,我在打字時看不到評論。

+0

感謝您的幫助。 – Virus721