是否可以确定是否从原型方法中调用实例方法?

时间:2011-03-03 14:42:34

标签: javascript prototype

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

因此,barf的实例方法,是Foo的实例。
另一方面,bazFoo的原型方法。

我想要的是:

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

2 个答案:

答案 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

相关问题