开发者

When I add an onclick event that references a method attached to an object, the method seems to lose all the properties associated with that object

开发者 https://www.devze.com 2023-04-12 22:18 出处:网络
I want to be able to pass one object to another, then set up events that execute different methods from the initial object.

I want to be able to pass one object to another, then set up events that execute different methods from the initial object.

var TEST = {}; 
//User-created object
TEST.testObj = function () { this.initialize.apply(this, arguments); };
TEST.testObj.prototype = {
    initialize: func开发者_运维百科tion(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);

Activating the event by clicking the div alerts undefined. It looks like it's calling the function sayHi, but a generic one not associated with an instantiated object.

Thanks!


You don't have a sayHi() function declared in this code. Just add this line

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

after the TEST.testObj.prototype... part. This will create a new function in TEST's prototype chain that you can call inside the testMenu object

EDIT The way you are binding the onclick event, this was referring to the div HTML element, not the object. This is the changed code that should work:

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号