NeailWiki

Because Change Happens.
JavaScript

Inherit

# 原型

每个JavaScript对象 (除 null) 在创建时都会关联另一个对象,这个对象就是我们所说的原型,每个对象都会从原型 “继承” 属性;每个对象 (除 null) 的__proto__指向该对象的原型。

# 原型链

对象的__proto__依次串联,会形成一条__proto__连起来的链条,递归访问__proto__最终到 null。

ps: 类比链表,每个节点的 next 都指向下一个节点,最终到 null;区别:节点并没有继承下一个节点的属性。

# 继承

# 原型链继承
function Parent() {
  this.property = true
}
Parent.prototype.getParentValue = function () {
  return this.property
}
function Child() {
  this.Childproperty = false
}
Child.prototype = new Parent()
Child.prototype.getChildValue = function () {
  return this.Childproperty
}
var instance = new Child()
console.log(instance.getParentValue())
# 构造函数继承
function Parent() {
  this.colors = ['red', 'blue', 'green']
}
function Child() {
  // 继承Parent
  Parent.call(this)
}
var instance1 = new Child()
var instance2 = new Child()
instance1.colors.push('black')
console.log(instance1.colors)  // [“red”, “blue”, “green”, “black”]
console.log(instance2.colors) // [“red”, “blue”, “green”]
# 组合继承(原型链 + 构造函数)
function Parent(name) {
    this.name = name;
  this.colors = ['red','blue','green'];
}

Parent.prototype.sayName = function() {
    console.log(this.name)
}

function Child(name, job) {
    Parent.call(this,name);
  this.job = job;
}

Child.prototype = new Parent();
Child.prototype.constructor = Parent;
Child.prototype.sayJob = function() {
    console.log(this.job);
}

console.log(new Child('xiaoming', 'student'));
# 原型式继承
function object(o) {
    function F() {}
  F.prototype = o;
  return new F();
}

var person = {
  name: 'Jiang',
  friends: ['Shelby', 'Court']
}
console.log(object(person))
console.log(Object.create(person))
# 寄生组合式继承
function inheritPrototype(Child, Parent) {
  var prototype = Object.create(Parent.prototype)
  prototype.constructor = Child
  Child.prototype = prototype
}

//ES6
// 继承
Object.setPrototypeOf(Child.prototype, Parent.prototype)
console.log(Child.prototype.constructor === Child) // true

# 附图

proto.jpg

Last Update: 2019-12-06 12:56:19 Source File