如何使用传递参数回调 JavaScript 对象属性

How can I callback JavaScript Object properties with passing argument?

本文关键字:JavaScript 对象 属性 回调 参数 何使用      更新时间:2023-09-26
function DarkWorld(name) {
        this.name = name;
        this.speed = 7;
        this.energyLevel = 10;
        this.flyAbility = true;
        this.description = function () {
            retun(this.name + " has the capability to hold the hummer");
        };
    }

我有上面的JavaScript代码,并尝试创建一个接受参数的回调函数,并访问对象的属性。

例如:我想为对象传递名称并访问energyLevel以在屏幕上打印。

有两种方法可以做到这一点:

您可以在参数中运行 DarkWorld 函数,也可以创建一个新实例:

假设这是您的另一个函数:

function run(darkworld) {
  alert(darkworld.name);
  alert(darkworld.speed);
}
//this one is questionable now... it was working but now its not
//this will work if you add "return self" or "return this" in your-
  //DarkWorld object
run(DarkWorld('apple'));
//or
var dw = new DarkWorld('apple');
run(dw);

更新

您可能也应该这样做,以便第一种方法起作用:

function DarkWorld(name) {
    //thank you icepickle for pointing this out to me
    if (typeof this === 'undefined' || !(this instanceof DarkWorld)) {
        return new DarkWorld(name);
    }
    var self = this;
    self.name = name;
    self.speed = 7;
    self.energyLevel = 10;
    self.flyAbility = true;
    self.description = function () {
        retun self.name + " has the capability to hold the hummer";
    };
}