简体   繁体   English

使用调用方法引用对象中的属性-JavaScript

[英]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 我可以调用getAge()方法

myObject.getAge();

and I'll get 33 in the pop-up. 我将在弹出窗口中得到33。

I'd like to get 23 in the alert box by changing the object this references. 我想通过更改引用的对象在警报框中获取23。 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. 我的理解是,通过将该呼叫方法,我改变在参考getAge()方法到的myObject ,然后应该允许警告框返回23 Unfortuntaely,结果仍然是33。

How do I change the this reference to that of myObject ? 如何将此引用更改为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. 查看如何在SO任何其他答案this工作。

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 . 这样,您可以使用所有具有age属性的对象。

Here's a working fiddle , check browser console too 这是一个有效的小提琴 ,也请检查浏览器控制台

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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