原型和原型链

256 阅读1分钟

图解原型和原型链

结论:

1,对象__proto__ === 其构造函数.prototype

2,Object.prototype 是所有对象的(直接或间接)原型

3,所有函数都是由 Function 构造的,即任何函数__proto__ === Function.prototype(),任何函数包括(Object / Array / Function)

原型与构造函数

  • 原型 每一个构造函数都拥有一个prototype属性,这个属性指向一个对象,也就是原型对象。当使用这个构造函数创建实例的时候,prototype属性指向的原型对象就成为实例的原型对象。

声明一个构造函数,为了区别与普通函数的区别,一般将首字母大写。

function Dog(color,name){
	this.color=color
    this.name=name
}
Dog.prototype.say=()=>{
	console.log('汪汪')
}

通过这个构造函数创建一个实例,并调用say方法

const dog1=new Dog()
dog1.say() //'汪汪'
  • 原型链 JavaScript中所有的对象都是由它的原型对象继承而来。而原型对象自身也是一个对象,它也有自己的原型对象,这样层层上溯,就形成了一个类似链表的结构,这就是原型链(prototype chain)。

Object函数的prototype属性是所有原型链的终点。因为对象是由Object()构造的。Object.prototype指向的原型对象也有自己的原型,它的原型为null

通过原型链就可以在JavaScript中实现继承,

function Animal(color){
	this.color=color
}
Animal.prototype.say=function(){} //动物可以叫

function Dog(color,name){
	Animal.call(this,color)
    this.name=name
}
// 以下将Dog.prototype.__proto__=Animal.prototype
function temp(){}
temp.prototype=Animal.prototype
Dog.prototype=new temp()

Dog.prototype.constructor=Dog
Dog.prototype.say=function(){consolr.log('汪汪')}

var dog=new Dog('白色','小花')
console.log(dog) //Dog {color: "白色", name: "小花"}

结语