如何使用传递参数回调 JavaScript 对象属性
How can I callback JavaScript Object properties with passing argument?
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";
};
}
相关文章:
- Chrome开发工具(如何知道我在调用哪个javascript对象)
- 循环遍历以数组为值的Javascript对象
- 从ajax请求中获取javascript对象
- 如何从对象的原型方法访问JavaScript对象属性
- 将XML转换为普通的旧JavaScript对象
- 通过引用传递JavaScript对象
- javascript对象操作:根据指定条件选择属性
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- 如何在异步函数中使用javascript对象
- 临时Javascript对象
- 如何在ASP中为用户控件添加Javascript对象网
- 使用数组向下搜索Javascript对象
- Rails将JavaScript对象存储到Model的有效方式
- JavaScript对象不是从原型链继承的
- 如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)
- SetInterval在javascript对象中表现怪异
- Javascript 对象和 this 关键字
- 如何在不知道关键字的情况下访问javascript对象值
- 在 JavaScript 对象中设置要使用的运算符的属性
- 如何搜索JavaScript对象并更改值