问题描述
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的原型方法
。
So, bar
is an instance method of f
which is an instance of Foo
.
On the other hand, baz
is a prototype method of Foo
.
我想要的是:
bar
应该返回 x
(传递给构造函数的参数),但是只有在原型方法中调用它(的方法) Foo.prototype
)。所以, bar
应检查当前执行上下文是否是 Foo.prototype
函数,然后只有 bar
应返回 x
。
bar
should return x
(the argument passed into the constructor function), but only if it is called from within a prototype method (a method of Foo.prototype
). So, bar
should check whether the current execution context is a Foo.prototype
function, and only then bar
should return x
.
在案例1中,当前执行上下文是全局代码,因此 bar
调用的返回值应为 undefined
。 (通过这个,我的意思是:我希望它在这种情况下返回undefined。)
In Case 1, the current execution context is Global code, so the return value of the bar
call should be undefined
. (By this, I mean: I want it to return undefined in this case.)
但是在这种情况下2,当前执行上下文是<$的函数代码c $ c> Foo.prototype 函数,因此 bar
调用的返回值应为 x
。
However in this case 2, the current execution context is Function code of a Foo.prototype
function, so the return value of the bar
call should be 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
从原型方法中调用 - > return x
Case 1: getX
is called "directly" -> return undefined
Case 2: getX
is called from within a prototype method -> return x
推荐答案
所以这是我自己的解决方案:
So this is my own solution:
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
。
As you can see, I had to define getX
as a local function of the Foo
constructor (and then assign this function to the instance via this.getX = getX;
. Inside getX
, I explicitly check whether getX.caller
is Foo.prototype.sqr
.
这篇关于是否可以确定是否从原型方法中调用实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!