【问题标题】:Error returning an object attribute in JS在 JS 中返回对象属性时出错
【发布时间】:2013-05-07 20:08:20
【问题描述】:
function Objecte(name){

    this.name=name;

}

Objecte.prototype.look=function(){

    return function(){

        alert(this.name);

    };

}

我正在尝试访问对象的属性,但是当我调用该函数时,它会提示未定义。

extintor = new Objecte("extintor");

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

【问题讨论】:

  • 包装它并返回一个函数不会改变 jQuery 将在其上使用 .call(this,event) 的事实,从而导致 this 引用单击的元素而不是您的 this
  • 你写的是 Objecte 而不是 Object
  • Object 在 JavaScript 中有意义!
  • 对象的实际名称是Objecte,不是这样的。不过还是谢谢。

标签: javascript jquery oop prototype


【解决方案1】:

this 没有词法定义。您需要捕获它的值,以确保返回的函数可以使用它。

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

你也可以使用$.proxy

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

在现代浏览器中或.bind()

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

【讨论】:

    【解决方案2】:

    您返回的匿名函数有另一个 this 上下文。

    因此你有两个选择:

    1.在外部创建对 this 的引用并在匿名函数中使用它

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

    2。使用包括 IE9+ 在内的所有主流浏览器都支持的Function.prototype.bind

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

    如果你不需要支持 IE8 及更低版本,那么第二个选项就是 - 对我来说它看起来更优雅。

    【讨论】:

      【解决方案3】:

      look 是否需要返回一个函数?我认为您正在尝试做的是:

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

      但是,此上下文中的this 将在函数执行时被解析,并且可以绑定到另一个对象。我认为在任何情况下使用对象的闭包声明而不是使用原型更清楚。你可以这样声明你的对象:

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

      缺点是每个 Objecte 类型的对象都会有自己的函数外观副本,但你上一次用完内存是什么时候? 另一个缺点是你不能从另一个对象继承,重写一个方法,然后从这个对象调用原始方法,因为它会丢失。然而,这是不利的..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-30
        • 2012-10-26
        • 2020-01-05
        相关资源
        最近更新 更多