简体   繁体   中英

Error returning an object attribute in JS

function Objecte(name){

    this.name=name;

}

Objecte.prototype.look=function(){

    return function(){

        alert(this.name);

    };

}

I'm trying to access the Object's attribute but when I call the function, it alerts undefined.

extintor = new Objecte("extintor");

$(document).on('dblclick',"#extintor",extintor.look());

this is not lexically defined. You need to capture its value in order to ensure that the returned function can use it.

Objecte.prototype.look=function(){
    var self = this;
    return function() {
        alert(self.name);
    };
}

You can also use $.proxy

Objecte.prototype.look=function(){
    return $.proxy(function() {
        alert(this.name);
    }, this);
}

or .bind() in modern browsers

Objecte.prototype.look=function(){
    return function() {
        alert(this.name);
    }.bind(this);
}

The anonymous function that you return has another context of this .

Therefore you have two options:

1. Create a reference to this outside and use it inside your anonymous function

Objecte.prototype.look = function() {
    var objecteInstance = this;
    return function() {
        alert(objecteInstance.name);
    };
}

2. Use Function.prototype.bind which is supported in all major browsers including IE9+

Objecte.prototype.look = function() {
    return function() {
        alert(this.name);
    }.bind(this);
}

If you don't need to support IE8 and lower, then the second option it is - as for me it looks more elegant.

Does look need to return a function? I think what you are trying to do is this:

Objecte.prototype.look=function(){

    alert(this.name);

}

However, this in this context will be resolved when the function is executed and could be bound to another object. I think it is clearer in any case to use the closure declaration of objects instead of using the prototype. You could declare your object this way:

function Objecte(name) {
    var that = this;

    this.name = name;

    this.look = function() {
        alert(that.name);
    }
}

The disadvantage is that every object of the type Objecte will have its own copy of the function look, but when was the last time you ran out of memory? Another disadvantage is that you can't inherit from another object, rewrite a method and later call the original method from this object, as it will be lost. However disadvantageous that is..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM