【问题标题】:Javascript object creation confusion with this keyword and prototype propertyJavascript 对象创建与 this 关键字和原型属性混淆
【发布时间】:2016-02-25 18:01:22
【问题描述】:

我尝试如下创建一个 javascript 对象

var SuperObj = function(){
    this.super = "super from Super";
    this.prototype.getSuper = function(){
        return this.super;
   }
}

上面的代码抛出错误:

TypeError: 无法设置未定义的属性“getSuper”

但是,当我尝试以下代码时,它起作用了。

var SuperObj = function(){
    this.super = "super from Super";
    SuperObj.prototype.getSuper = function(){
        return this.super;
    }
}

我想知道区别。我认为在第一种情况下,两个“this”共享相同的执行环境。为什么我们可以使用它来添加属性而不是原型属性中的功能?

【问题讨论】:

  • 您可能应该在构造函数之外声明原型。仅在其中声明带有“this”的实例数据。比如:var SuperObj = function(){this.super = "super from Super";}; SuperObj.prototype.getSuper = function(){return this.super;};

标签: javascript this self


【解决方案1】:

SuperObj.prototypethis.prototype 不是同一个东西。对象实例上没有名为 prototype 的默认属性。

以下将做你想做的事

var SuperObj = function(){
  this.super = "super from Super";
  // Here, this.constructor === SuperObj
  this.constructor.prototype.getSuper = function(){
      return this.super;
  }
}

说了这么多,我从来没有找到在构造过程中设置原型属性的有效案例。原型属性设置一次,对象属性随每个构造函数设置。见Javascript inheritance: call super-constructor or use prototype chain?

【讨论】:

    【解决方案2】:

    当您创建一个新的对象实例时,您无法访问 prototipe 属性,因为不存在任何一个。

    如果你想通过 this 访问原型属性,你必须使用以下模式:

    this.constructor.prototype.method
    

    【讨论】:

      猜你喜欢
      • 2011-10-19
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      相关资源
      最近更新 更多