当我添加一个引用附加到对象的方法的onclick事件时,该方法似乎丢失了与该对象关联的所有属性

时间:2011-10-13 08:59:35

标签: javascript events object methods

我希望能够将一个对象传递给另一个对象,然后设置从初始对象执行不同方法的事件。

var TEST = {}; 
//User-created object
TEST.testObj = function () { this.initialize.apply(this, arguments); };
TEST.testObj.prototype = {
    initialize: function(a) {   
        this.a = a;
    },
    sayHi: function() {
    alert(a);
}
} 
//Menu accosiated with that class of objects 
TEST.testMenu = function () { this.initialize.apply(this, arguments); };
TEST.testMenu.prototype = {
    initialize: function(obj) {
        this.obj = obj;
        var menuItem = document.createElement('div');
        menuItem.innerHTML = 'Say Hi!';
        menuItem.onclick = this.obj.sayHi;
        document.body.appendChild(menuItem);
    }
}

t1 = new TEST.testObj('Test Object');
menu = new TEST.testMenu(t1);

单击div alert undefined来激活事件。看起来它正在调用函数sayHi,而是一个与实例化对象无关的泛型函数。

谢谢!

1 个答案:

答案 0 :(得分:1)

您没有在此代码中声明的sayHi()函数。只需添加此行

即可
TEST.testObj.prototype.sayHi = function() {alert('hi')}

TEST.testObj.prototype...之后。这将在TEST的原型链中创建一个新函数,您可以在testMenu对象中调用

修改 你绑定onclick事件的方式, this 指的是div HTML元素,而不是对象。这是应该有效的更改代码:

var TEST = {}; 
        //User-created object
        TEST.testObj = function () { this.initialize.apply(this, arguments); };
        TEST.testObj.prototype = {
            a: null, 
            initialize: function(a) {
                this.a = a;
            },
            sayHi: function() {
            alert(this.a);
        }
        } 
        //Menu accosiated with that class of objects 
        TEST.testMenu = function () { this.initialize.apply(this, arguments); };
        TEST.testMenu.prototype = {
            initialize: function(obj) {
                this.obj = obj;
                var menuItem = document.createElement('div');
                menuItem.innerHTML = 'Say Hi!';
                menuItem.onclick = function() { obj.sayHi(); }
                document.body.appendChild(menuItem);
            }
        }

        t1 = new TEST.testObj('Test Object');
        menu = new TEST.testMenu(t1);