跳至主要內容

JavaScript 面向对象-原型继承

h7ml小于 1 分钟约 240 字

JavaScript 面向对象-原型继承

JavaScript原型
JavaScript原型
JavaScript原型链
JavaScript原型链

原型链继承

function Person(name) {
  this.name = name;
}
Person.prototype.fn = function () {
  console.log('parent');
};
function Child() {}
Child.prototype = new Person('name'); // new 之后 只是实例化的对象,下面有 __proto__
Child.prototype.constructor = Child; // 手动修改回来
var child = new Child();
// 在原型上继承,子类不能修改和传参进去

对象冒充继承(借用构造函数

function Parent(name) {
  this.name = name;
}
Parent.prototype.fn = function () {
  console.log('parent');
};
function Child(name) {
  Parent.call(this, name);
}
var child = new Child('xiaohong');

组合继承

function Parent(name) {
  this.name = name;
}
Parent.prototype.eat = function () {
  console.log('11');
};
function Child(name) {
  Person.call(this, name);
}
Child.prototype.eat = Parent.prototype;
Child.prototype.constructor = Child;

寄生式组合继承

function Parent(name) {
  this.name = name;
}
Parent.prototype.aa = function () {
  console.log('aa');
};

function inherit(Child, Parent) {
  function Super() {}
  Super.prototype = Parent.prototype;
  Child.prototype = new Super();
  Child.prototype.constructor = Child;
}

function Child() {}
inherit(Child, Parent);
var child = new Child();

for...in 继承

// 遍历父原型对象
for (funName in Person.prototype) {
  // 子构造函数原型属性 = 父原型对象的属性
  NewPerson.prototype[funName] = Person.prototype[funName];
}

Object.create()继承

create 创建新对象

NewPerson.prototype = Object.create(Person.prototype);