简体   繁体   中英

Referencing Object Properties in Javascript

If I have The code:

function RandomObjectThatIsntNamedObjectWhichIOriginallyNamedObjectOnAccident() {
    this.foo = 0;
    this.bar = function () {
        this.naba = 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM