[英]Is it possible to determine whether an instance method was called from within a prototype method?
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
是必须从原型方法( Foo.prototype
方法)中调用x
。 因此, bar
应该检查当前执行上下文是否是Foo.prototype
函数,然后bar
应该返回x
。
在情况1中,当前执行上下文是Global代码,因此bar
调用的返回值应为undefined
。 (通过这个,我的意思是:在这种情况下,我希望它返回未定义的。)
但是,在这种情况2下,当前执行上下文是Foo.prototype
函数的Function代码,因此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
在情况1中,当前执行上下文是全局代码,因此bar调用的返回值应未定义。
您正在使用闭包,这就是为什么getX方法访问变量x的原因。 它的javascript行为符合预期。
所以这是我自己的解决方案:
function Foo(x) {
function getX() {
return getX.caller === Foo.prototype.sqr ? x : void 0;
}
this.getX = getX;
}
Foo.prototype.sqr = function() {
var x = this.getX();
return x * x;
};
var f = new Foo(3);
console.log( f.getX() ); // logs undefined
console.log( f.sqr() ); // logs 9
如您所见,我必须将getX
定义为Foo
构造函数的本地函数(然后通过this.getX = getX;
将此函数分配给实例。在getX
,我明确检查getX.caller
是否为Foo.prototype.sqr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.