简体   繁体   中英

Using Call Method to Reference a Property in an Object - JavaScript

I have the following object:

myObject = {
    color: "yellow",
    age: 23,
    nationality: "usa",
    getAge: function(){
        var age = 33;
        alert(age);
    }
}

I can call the getAge() method

myObject.getAge();

and I'll get 33 in the pop-up.

I'd like to get 23 in the alert box by changing the object this references. I am thinking something like the following

myObject.getAge.call(this);

My understanding is that by passing this to the call method, I am changing the reference of this in the getAge() method to that of myObject , which then should allow the alert box to return 23. Unfortuntaely, the result is still 33.

How do I change the this reference to that of myObject ?

myObject = {
    color: "yellow",
    age: 23,
    nationality: "usa",
    getAge: function(){
        alert(this.age);
    }
}
myObject.getAge();

You could be better off with a constructor, since this is getting mangled in there. See any other answer on SO on how this works.

function person(){
    this.color = "yellow";
    this.age = 23;
    this.nationality = "usa";
}
person.prototype.getAge = function(){
    alert(this.age);
};

var p = new person();
p.getAge();

Why not simply:

myObject = {
    color: "yellow",
    age: 23,
    nationality: "usa"
}
myObject.getAge = function() { return myObject.age; };

You could do it like this:

function getAge(){
  alert(this.age)
}

myObject = {
    color: "yellow",
    age: 23,
    nationality: "usa"
}

getAge(myObject) // Alerts undefined

getAge.call(myObject) // Alerts 23

This way you can use all kind of object that have an age property .

Here's a working fiddle , check browser console too

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