通过函数添加到对象

Adding to an object through a function

本文关键字:对象 添加 函数      更新时间:2023-09-26

我目前正试图通过函数添加到对象中。

我的代码是:

var ob = {};
function add(f, fun) {
    ob[f] = fun();
}
add('hi', function() {
    alert('hello')
})
ob.hi()​

因此,假设将ob更改为:

var ob = {
     hi: function(){
      alert('hello')
     }
}

它确实会提醒hello,但只是从添加函数的触发(我想停止)开始,而不是从ob.hi()函数开始。

谢谢你的帮助。如果你愿意,你也可以检查小提琴

您正在执行函数并将其返回值分配给属性。您需要将对函数的引用改为分配给属性。更改add功能:

function add(f, fun) {
    ob[f] = fun; //No invoking parentheses!
}

这是一把最新的小提琴。

如果你看一看你原来小提琴里的控制台,你会发现出了什么问题:

未捕获的类型错误:对象#<Object>的属性"hi"不是功能

将函数添加为对象的属性:

ob['hi'] = function() {
    alert('hello')
};

ob[funname] = fun;

如果函数在其他地方定义。

不要为了设置属性而编写add函数。用自定义setter替换语言的标准特性不会使代码更可读。

别忘了,您可以在javascript:中定义类

function Rect(x,y,w,h){
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
}
Rect.prototype.contains = function(x, y) {
    return x>=this.x && x<=this.x+this.w && y>=this.y && y<=this.y+this.h;
};

创建为new Rect(0, 1, 2, 3)的所有对象都具有contains功能。