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。)
但是在这种情况下2,当前执行上下文是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
被称为“直接” - >返回undefined
情况2:从原型方法中调用getX
- >返回x
答案 0 :(得分:0)
在案例1中,当前执行上下文是全局代码,因此条形码调用的返回值应该是未定义的。
你正在使用一个闭包,这就是方法getX可以访问变量x的原因。它的javascript按预期运行。
答案 1 :(得分:0)
所以这是我自己的解决方案:
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;
将此函数分配给实例。内部{{1} },我明确检查getX
是否为getX.caller
。