原型、原型链

108 阅读1分钟

原型定义

原型是function对象的一个属性,它定义了构造函数制造出的对象的公共祖先。通过该构造函数产生的对象,可以继承该原型的属性和方法。原型也是对象。

对象如何查看原型 -> 隐式属性 __proto__

对象如何查看对象的构造函数 -> constructor

从属关系

prototype -> 函数的一个属性:普通对象 {}

__proto__ -> 对象Object的一个属性:普通对象 {}

对象的__proto__保存着该对象的构造函数的prototype

function Person(){

}
console.log(Person.prototype);

const person = new Person();
console.log(person.__proto__);

console.log(person.__proto__ === Person.prototype); // true

console.log(Person.prototype.__proto__ === Object.prototype); // true

console.log(Object.prototype.__proto__); // null

利用原型特点和概念,可以提取共有属性

// 共有属性
Car.prototype.lang = 4900;
Car.prototype.height = 1400;
Car.prototype.carName = 'BMW';
function Car(color, owner){
  this.owner = owner;
  this.color = color;
}

const car = new Car('green', '李四');
const car1 = new Car('red', '张三');
console.log(car, car1);
console.log(car.lang, car1.lang); // 4900 4900

原型链

原型链的链接点是 __proto__

Grand.prototype.lastName = 'Liu';
function Grand(){

}
const grand = new Grand();
Father.prototype = grand;
function Father(){
  this.name = 'xuming';
}
const father = new Father();
Son.prototype = father;
function Son(){
  this.hobbit = 'smoke';
}
const son = new Son();

console.log(son.hobbit); // smoke
console.log(son.name); // xuming
console.log(son.lastName); // Liu

Object.create(原型);

const obj = {
  name: 'liu'
}
const obj1 = Object.create(obj); // obj1的原型是obj

Person.prototype.name = 'liu';
function Person(){

}
const person = Object.create(Person.prototype); // person的原型是Person.prototype

const obj2 = Object.create(null); //创建无原型对象 没有toString()

toString()

undefined.toString() // 报错, 是原始值,没有原型所以没有toString()

null.toString() // 报错, 是原始值,没有原型所以没有toString()

document.write(obj) // 会先调用toString()再输出到页面,如果自身没有toString()就从原型上找