简体   繁体   English

Javascript对象创建与此关键字和prototype属性的混淆

[英]Javascript object creation confusion with this keyword and prototype property

I try to create a javascript object as follows 我尝试创建一个JavaScript对象,如下所示

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

the code above throw errors: 上面的代码抛出错误:

TypeError: Cannot set property 'getSuper' of undefined TypeError:无法设置未定义的属性“ getSuper”

However when I tried the following code it worked. 但是,当我尝试以下代码时,它起作用了。

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

I want to know the difference. 我想知道区别。 I think in the first case, both 'this' share the same execute environment. 我认为在第一种情况下,两个“ this”共享相同的执行环境。 How come we can use it to add property but not function in prototype property? 我们怎么能用它添加属性而不是原型属性?

SuperObj.prototype and this.prototype are not the same things. SuperObj.prototypethis.prototype是不同的东西。 There is no default property called prototype on object instances. 在对象实例上没有称为prototype默认属性。

The following will do what you are trying to do 以下将完成您想做的事情

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

Having said all that, I have never found a valid case for setting prototype properties during construction. 说了这么多,我还没有找到在构造过程中设置原型属性的有效案例。 Prototype properties are set once, object properties are set with every constructor. 原型属性设置一次,对象属性设置每个构造函数。 See Javascript inheritance: call super-constructor or use prototype chain? 请参阅Javascript继承:调用超级构造函数还是使用原型链?

When you create a new object instance you can't access to prototipe property because doesn't exist any one. 创建新的对象实例时,您将无法访问prototipe属性,因为属性不存在。

If you want to access to the prototype property through this you have to use the following pattern: 如果要通过此方法访问prototype属性,则必须使用以下模式:

this.constructor.prototype.method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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