开发者

Referencing Object Properties in Javascript

开发者 https://www.devze.com 2023-03-31 19:12 出处:网络
If I have The code: function RandomObjectThatIsntNamedObjectWhichIOriginallyNamedObjectOnAccident() { this.foo = 0;

If I have The code:

function RandomObjectThatIsntNamedObjectWhichIOriginallyNamedObjectOnAccident() {
    this.foo = 0;
    this.bar = function () {
        this.naba 开发者_如何学Go= function () {
            //How do I reference foo here?
        }
    }
}


You need a self reference:

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


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


Try the following

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


First: Don't name your function Object, it will shadow the global Object constructor.

I don't see a reason why you have to assign naba inside bar to the instance. Why are you doing this? You can assign both bar and naba to the functions prototype:

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

MyConstructor.prototype.bar = function () {

};

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

Eventually it depends on how you are calling the naba function. The fact that you are assigning it to this suggests you want to call it with

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

If you want to add naba only after bar was called, you can still access foo via this.foo:

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

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

If you want a proper/better answer, you have to show how you are going to use naba.


Interestingly enough, you don't need to do anything special.

The this reference works:

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

Since you're assigning "methods" always to the same reference, this will still point to it inside bar, and later inside naba.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号