在Javascript中引用对象属性

时间:2011-08-29 19:44:27

标签: javascript oop object

如果我有代码:

function RandomObjectThatIsntNamedObjectWhichIOriginallyNamedObjectOnAccident() {
    this.foo = 0;
    this.bar = function () {
        this.naba = function () {
            //How do I reference foo here?
        }
    }
}

5 个答案:

答案 0 :(得分:11)

您需要self参考:

function RandomObjectThatIsntNamedObjectWhichIOriginallyNamedObjectOnAccident() {
    var self = this;
    this.foo = 0;
    this.bar = function () {
        this.naba = function () {
            self.foo; //foo!
        }
    }
}

答案 1 :(得分:6)

function SomeObject() {
    var self = this;
    this.foo = 0;
    this.bar = function () {
        this.naba = function () {
            self.foo;
        }
    }
}

答案 2 :(得分:3)

尝试以下

function SomeObject() {
    var self = this;
    this.foo = 0;
    this.bar = function () {
        this.naba = function () {
            //How do I reference foo here?
            self.foo
        }
    }
}

答案 3 :(得分:1)

首先:不要为你的函数Object命名,它会影响全局Object构造函数。

我没有看到您必须在naba内为bar分配实例的原因。你为什么做这个?您可以将barnaba分配给函数原型:

function MyConstructor() {
    this.foo = 0;
}

MyConstructor.prototype.bar = function () {

};

MyConstructor.prototype.naba = function () {
    // this.foo
};

最终,它取决于您正在调用naba函数的 。您将其分配给this这一事实表明您想要使用

进行调用
var obj = new MyConstructor();
obj.naba();

如果您只想在调用naba后添加bar,您仍然可以通过foo访问this.foo

MyConstructor.prototype.bar = function () {
    if(!this.naba) {
        this.naba = function() {
            // this.foo
        };
    }
};

var obj = new MyConstructor();
obj.bar();
obj.naba();

如果你想要一个正确/更好的答案,你必须说明你将如何使用naba

答案 4 :(得分:0)

有趣的是,你不需要做任何特别的事情。

this参考有效:

function SomeObject() {
  this.foo = 0;
  this.bar = function () {
    this.naba = function () {
      alert(this.foo); // this works!
    }
  }
}

由于您始终将“方法”分配给同一参考,this仍将指向bar内,稍后位于naba内。

相关问题