【问题标题】:Clarifications on prototypal inheritance关于原型继承的说明
【发布时间】:2016-02-20 21:38:23
【问题描述】:

我有一个原型继承,如下所示,Student 扩展了Guru。我有三个问题,谁能解释一下。

function Guru(name){
  this.name = name;
}

Guru.prototype.copy = function(){
  return this.constructor(this.name);
}

function Student(name){
  Guru.call(this)
  this.name = name;
}

Student.prototype = Object.create(Guru.prototype);
Student.prototype.constructor = Student;
var stu = new Student("John Cena");

console.log(stu.constructor);
console.log(stu.__proto__);
  1. 我们为什么要避免Student.prototype = new Guru();
  2. 这两者有什么区别:

    console.log(stu.constructor);
    console.log(stu.__proto__);
    

    打印以下内容:

    [Function: Guru]
    Guru { constructor: [Function: Student] }
    
  3. constructor.prototypeprototype.constructor 之间的区别?我们在javascript中有constructor.prototype吗?

【问题讨论】:

  • 这里有一些精彩的答案stackoverflow.com/questions/572897/…,尤其是第二个答案。我还建议阅读有关编程范例的文章。
  • 每个帖子只问一个问题。
  • 顺便说一句,第一个问题回答herethere
  • 你所有的学生都是大师?哇。顺便说一句,copy 方法错过了new

标签: javascript inheritance prototype


【解决方案1】:
  1. 我们为什么要避免Student.prototype = new Guru()

因为Guru 构造函数需要一个实例,而不是子类。在该构造函数中创建的属性应直接分配给实例。

在你的情况下,这并不重要,但想象一下:

function C1() { this.o = []; }
function C2() {}
C2.prototype = new C1();
var c1a = new C1(), c1b = new C1(),
    c2a = new C2(), c2b = new C2();
c1a.o.push(123);
c2a.o.push(456);
c1b.o; // []    -- The property is NOT shared among C1 instances
c2b.o; // [456] -- The property is shared among all Sub instances
  1. stu.constructorstu.__proto__ 有什么区别?

当您创建Student 构造函数时,它会自动接收带有constructor 属性的prototype,该属性指向Student

相反,__proto__ 是一个 getter,它返回对象的 [[Prototype]]。请注意,这不是很标准(仅在浏览器附件中定义),您应该改用Object.getPrototypeOf

因此,stu.constructor(继承自Student.prototype)是Student。而stu.__proto__(继承自Object.prototype)是Student.prototype

  1. constructor.prototypeprototype.constructor 之间的区别?

在原型上使用constructor.prototype 毫无意义,因为它给出了相同的原型(假设它没有被更改)。

在实例上使用constructor.prototype 会给出它继承自的原型(假设它没有被隐藏也没有被更改)。

在构造函数上使用prototype.constructor 是没有意义的,因为它给出了相同的构造函数(假设它没有被改变)。

【讨论】:

  • @ShankarGuru 是的,通常这是不可取的。
猜你喜欢
  • 2022-10-13
  • 2017-12-21
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 2011-02-17
  • 1970-01-01
  • 2019-09-04
  • 2015-07-07
相关资源
最近更新 更多