原型prototype
这个 prototype 是定义构造函数构造出的每个对象的公共祖先 有点像python里的类方法类属性
所有被该构造函数构造出的对象都可以继承原型上的属性和方法
proto属于实例化对象,实际上是实例化对象 this 里的一个属性
Car.prototype.name="Benz"
var car = new Car()
car.name = "BWM"
function Car(){
/* this:{
name:"BWM",
__proto__:Car.prototype
}
*/
}
找的时候先找 this,没有的话沿着proto去找原型
//Car.prototype.constructor->Car()->prototype
圣杯继承
function Teacher(){
this.name = '张三'
}
Teacher.prototype = {
pskill:'js'
}
var t = new Teacher()
function Student(){
this.name = '李四'
}
Student.prototype=Teacher.prototype
Student.prototype.age = 18
var s = new Student()
console.log(t) //t的__proto__里的原型也加了个age属性
console.log(s)
上述情况就造成了污染,为了隔离 Teacher 和 Student 使得 Student 可以继承 Teacher 并且在 Student 原型上加属性不会影响到 Teacher 的原型 因此在中间用一个空的对象转一次 空对象的原型指向 Teacher 的原型
function Teacher(){
this.name = '张三'
}
Teacher.prototype = {
pskill:'js'
}
var t = new Teacher()
function Student(){
this.name = '李四'
}
function Buffer(){}
Buffer.prototype=Teacher.prototype
var buffer = new Buffer()
Student.prototype = buffer
var s = new Student()
Student.prototype.age = 18
console.log(t) //t的__proto__里的原型也加了个age属性
console.log(s)
用闭包去包装这个过程
var inherit = (function(){
var Buffer = function(){}
return function(Target,Origin){
Buffer.prototype = Origin.prototype
Target.prototype = new Buffer
Target.prototype.constructor = Target
Target.protoType.super_class = Origin
}
})()