function Foo(x) {
this.bar = function() { return x; /* but not always */ }
}
Foo.prototype.baz = function() {
return this.bar(); // Case 2 - should return x
};
var f = new Foo(3);
f.bar(); // Case 1 - should return undefined
f.baz(); // should return x which is 3 in this case
所以,bar
是f
實例方法這是Foo
一個實例。
另一方面,baz
是Foo
的原型方法。是否可以確定實例方法是否在原型方法中調用?
我想是這樣的:
bar
應該返回x
(傳遞到構造函數的參數),但只有當它是從一個原型法(的Foo.prototype
的方法)中調用。因此,bar
應檢查當前執行上下文是否爲Foo.prototype
函數,並且只有bar
應該返回x
。
在情況1中,當前執行上下文是全局代碼,所以bar
調用的返回值應爲undefined
。 (這個,我的意思是:我希望它在這種情況下返回undefined。)
但是在這種情況下,當前執行上下文是Foo.prototype
函數的函數代碼,所以bar
調用的返回值應該是x
。
可以這樣做嗎?
更新:一個真實世界的例子:
function Foo(x) {
this.getX = function() { return x; /* but not always */ }
}
Foo.prototype.sqr = function() {
var x = this.getX(); // should return 3 (Case 2)
return x * x;
};
var f = new Foo(3);
f.getX(); // should return undefined (Case 1)
f.sqr(); // should return 9
情況1:getX
「直接」 稱爲 - >返回未定義
情況2:getX
從原型方法中調用 - > return x
我想你可以使用arguments.callee.caller,但它真的被棄用,不應該使用 – 2011-03-03 14:48:21
爲什麼你需要它嗎?我找不到它的有用性... – 2011-03-03 14:56:05
@Martin看看我的問題中的更新。我正在將一個數字傳遞給'Foo'。我希望這個數字可以被原型方法所訪問,但是我不希望這個數字能夠在不使用原型方法的情況下被直接獲取。 – 2011-03-03 15:02:56