2013-07-06 27 views
2

有兩個JavaScript「對象類」 MyClass1的MyClass2被叫方的名稱,其中在MyClass1的方法(FOO電話的方法()在MyClass2中,我需要動態識別誰在調用函數原型moo from moo本身。如何識別AA的JavaScript原型法從另一個原型法

當我使用流行的建議arguments.callee.caller訪問器,我不能派生名稱。總的來說,我需要從方法moo知道它是從MyClass1的moo方法或其他方法調用的。

function MyClass1() { 
    this.myAttribute1 = 123; 
} 

MyClass1.prototype.foo = function() { 
    var myclass2 = new MyClass2(); 
    myclass2.moo(); 
}; 


function MyClass2() { 
    this.mySomething = 123; 
} 

MyClass2.prototype.moo = function() { 
    console.log("arguments.callee.caller.name = " + 
     arguments.callee.caller.name); 
    console.log("arguments.callee.caller.toString() = " + 
     arguments.callee.caller.toString()); 
}; 

在上面的例子arguments.callee.caller.name的結果是空的,而呼叫者的toString()方法示出了功能的身體,但不是其所有者類或名稱的方法的。

此需求的原因是我想要創建一個調試方法,以跟蹤方法調用。我廣泛使用Object類和方法。

回答

3

您需要命名您的函數表達式。試試這個:

function MyClass1() { 
    this.myAttribute1 = 123; 
} 

MyClass1.prototype.foo = function foo() { // I named the function foo 
    var myclass2 = new MyClass2; 
    myclass2.moo(); 
}; 

function MyClass2() { 
    this.mySomething = 123; 
} 

MyClass2.prototype.moo = function moo() { // I named the function moo 
    console.log("arguments.callee.caller.name = " + 
     arguments.callee.caller.name); 
    console.log("arguments.callee.caller.toString() = " + 
     arguments.callee.caller.toString()); 
}; 

觀看演示:http://jsfiddle.net/QhNJ6/

的問題是,你要指定它沒有名字MyClass1.prototype.foo功能。因此它是name屬性是一個空字符串("")。你需要命名你的函數表達式,而不僅僅是你的屬性。


如果你想找出arguments.callee.caller是否是從MyClass1那麼你就需要這樣做:

var caller = arguments.callee.caller; 

if (caller === MyClass1.prototype[caller.name]) { 
    // caller belongs to MyClass1 
} else { 
    // caller doesn't belong to MyClass1 
} 

不過請注意,這種方法取決於功能是一樣的財產name名稱定義在MyClass1.prototype。如果您將名爲bar的函數指定爲MyClass1.prototype.foo,那麼此方法將不起作用。

+0

謝謝。我甚至不知道有可能命名方法功能。很簡單。順便說一句,你知道如何確定來自Class MyClass1的調用者(foo)嗎? – gextra

+1

@gextra是的,這是可能的。我更新了我的答案,以演示如何。 –