How to avoid “this” refering to the DOM element, and refer to the object

后端 未结 3 632
死守一世寂寞
死守一世寂寞 2021-01-16 11:48

I have a problem that I can\'t work around.

The context is: I want to have an inheritance chain, and a method of objects that belong to this inheritance has to be a

3条回答
  •  耶瑟儿~
    2021-01-16 12:48

    The first problem in your jsfiddle is that self is a local variable for Constructor and it is not available outside of the function. What you think about the following code:

    var Constructor = function(name, value) {
        var self = this;
        self.name = name;
        self.value = value;
        self.someHandler = function(e) {
            e.target.innerHTML = self.name + self.value; // self undefined    
        }
        return self;
    };
    
    var myObject = Constructor('myName', 'myValue');
    document.getElementById('myDiv').onclick = myObject.someHandler;
    

    JsFiddle -> http://jsfiddle.net/ZcG3J/4/

    Is it structured as you want?

提交回复
热议问题