首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么this.prototype在构造函数中没有定义?

为什么this.prototype在构造函数中没有定义?
EN

Stack Overflow用户
提问于 2018-07-16 08:54:15
回答 1查看 724关注 0票数 0

tl;dr:可以使用Object.getPrototypeOf(this)访问其构造函数中的对象Object.getPrototypeOf(this)。这并不是简单的:this.prototype。为什么?

我有个简单的问题。我认为Ecmascript-5专家将帮助我揭示神秘的this

我的目标是编写一些引用代码,通过嵌入在IIFE中的构造函数来声明类(立即调用函数表达式),并在需要时将这种教学模式作为模板应用。这个构造的好处是它允许声明实例和类数据。在prototype对象中拥有所有方法也很好。这是我想出来的

代码语言:javascript
复制
var Person = (function(){
  // class scope variables
  var persons = [];
  // constructor with variables
  return function(name, age){
   // gets the prototype of Object: useful for defining methods
   // could also be: proto = Person.prototype
   var proto = Object.getPrototypeOf(this);
   // instance variable
   this.name = name;
   this.age = age;
   persons.push(this);
   // method which accesses to both class and instance variables
   if (!proto.stats) // avoids re-inventing the wheel upon each New
    proto.stats = function() {
     for(var acc=0, n=0; n<persons.length; n++)
      acc+=persons[n].age;
     return this.name + ": " + 
            this.age + " (average: " + acc/n + ")";
    };
   return this; // not required, just to remember what it does normally
  };
})(); // IIFE
// a classic method (cannot access class variables)
Person.prototype.toString = function(){
  return this.name + ": " + this.age + " years old";
};

我实现了我的目标,这个模式看起来相当可扩展,方法位于prototype对象中,而不是实例中。然而,我仍然有些奇怪的事情:我首先想使用的是proto,而不是构造器中的proto声明和使用。但这是undefined。怎么会这样?

旁注:我在类似的问题上发现了一些提示,但对我的理解来说,这与我的理解没有任何关系。

感谢您的时间,知识和关注。

EN

回答 1

Stack Overflow用户

发布于 2018-07-16 09:06:05

试着遵循下面的例子。我还建议您阅读这本书http://shop.oreilly.com/product/9780596517748.do,以了解您正在JavaScript做什么。

代码语言:javascript
复制
function Car() {
  console.log(this)                 // I'm the new Car "instance"
  console.log(typeof this)          // I'm of type object
  console.log(this instanceof Car)  // but I'm an instance of Car
  console.log(this.prototype)       // I'm undefined because __proto__ is the reference to the prototype
  console.log(this.__proto__)       // This is the prototype
}

Car.prototype.drive = function drive() {
  console.log('I\'m driving')
}

const fiat = new Car()
fiat.drive()

干杯,

灰分

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51358013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档