在不同的上下文中访问自身内部的类引用

Accessing reference of Class inside itself while in different context

本文关键字:内部 引用 上下文 访问      更新时间:2023-09-26
function Foo(){
}
Foo.prototype={
    foo:'some text'
    ,bar:function(){
        console.log('Want to be able to retrieve foo of Foo',this.foo);
    }
}
var instance=new Foo();
instance.bar.apply({});

这里是jsfiddle的链接:

http://jsfiddle.net/dnJFt/1/

我试着玩的范围,把类的建设内部包装与var self里面。返回instance of Class后,参照var self:

function Foo() {
    var self;
    function Foo_in(){
    }
    Foo_in.prototype={
        foo:'some text'
        ,bar:function(){
            console.log('Want to be able to retrieve foo of Foo',self);
        }
    }
    return self=new Foo_in();
}
var instance=new Foo();
instance.bar.apply({});

这是jsfiddle的链接:http://jsfiddle.net/dnJFt/2/

但我的解决方案是坏的,因为每次我重建Class和它的原型方法。

有更简单的解决方案吗?

试一试:

var Foo = (function () {
    var Foo_in = function (){};
    Foo_in.prototype={
        foo:'some text',
        bar:function(){
            console.log('Want to be able to retrieve foo of Foo',self);
        }
    }
    var self = new Foo_in();
    return Foo_in;
})();

使用这段代码,您在自动调用函数作用域中创建类,并在该作用域中声明self变量,以便在类方法中可以访问它,然后返回将分配给全局Foo变量的类引用。通过这种方式,您可以获得对self变量的引用,并且只需创建一次类。

您可以将Foo.prototype对象作为参数传递:

function Foo() {}
Foo.prototype = {
    foo: 'some text',
    bar: function ( proto ) {
        console.log( 'foo: ', proto ? proto.foo : this.foo );
    }
}
var instance = new Foo();

所以…

instance.bar() // 'some text'
instance.bar.apply( {}, [ Foo.prototype ] ) // 'some text'

现场演示: http://jsfiddle.net/wpyZN/


替代用法:

instance.bar() // 'some text'
instance.bar.apply( {}, [ instance ] ) // 'some text'

现场演示: http://jsfiddle.net/wpyZN/1/


更新:我对闭包解决方案的看法:

var Foo = (function () {
    function F() {}
    var proto = F.prototype = {
        foo: 'some text',
        bar: function () {
            console.log( 'foo: ', proto.foo );
        }
    }
    return F;
})();

var instance = new Foo();
instance.bar.apply( {} );

现场演示: http://jsfiddle.net/KT7vU/

因此,bar方法使用proto引用来访问foo值…

在bar中执行this.foo不起作用(apply-调用更改了this的值,因此它不再指向实例)。因此,我们必须提供对原型对象的手动引用,该对象保存所需的foo值。最合适的方法是我上面的代码中提供的方法…