概念:一个对象可以访问另一个对象上的成员。在javascript,对象与对象之间是通过prototype属性来实现成员和方法的共享(继承)。
function Animal(name){
this.name = name
}
Animal.prototype.eat=function(){
console.log(this.name + 'can eat other small animals .')
}
var animal1 = new Animal('snake')
var animal2 = new Animal('tiger')
animal1.eat===animal2.eat //true
//animal1.eat和animal2.eat都指向 Animal.prototype.eat ,实现方法共享(继承)
原型:就是函数的prototype属性所引用的对象
原型继承的原理:一个对象能够访问它的proto属性所指向的对象上的成员和方法(当然如果这个对象本身有它要访问的成员和方法,就不去它的proto属性所指向的对象上查找,逐级向上查找,直至null,则返回undefined)
var a = {}
//继承关系:a -> Object.prototype ->null
// a.hasOwnProperty 就是访问的Object.prototype上的hasOwnProperty方法。因为a本身并没有hasOwnProperty方法,而a.__proto__属性指向 Object.prototype ,且Object.prototype上有hasOwnProperty方法
概念:js在创建对象(不论是普通对象还是函数对象)的时候,都有一个叫做proto的内置属性,用于指向创建它的函数对象的原型对象prototype把这个有proto的对象串起来,直到Object.prototype甚至到null的链,叫做原型链。
本质:链上的每一个对象都是通过proto属性连接起来的。
...js
var a = {};
//原型链:a -> Object.prototype -> null
var arr=[];
//原型链:arr -> Array.prototype -> Object.prototype -> null
function Person(){}
var p1 = new Person()
//原型链:p1 -> Person.prototype -> Object.prototype -> null
...
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.run = function(){
console.log(this.name + 'can run !')
}
var p1 = new Person('Jeck',23)
var p2 = new Person('Rose',22)
p1.run === p2.run //true
// p1 和 p1 都能访问 Person.prototype上的run方法
Person.prototype = {
eat:function(){
console.log(this.name + 'can eat !')
}
}
var p1 = new Person('Jeck',23)
var p2 = new Person('Rose',22)
p1.eat === p2.eat //true
// p1 和 p1 都能访问 Person.prototype上的eat方法
function Child(name.age){
this.name = name
this.age = age
}
//IE8以下不支持Object.create()方法
//兼容代码
if(!Object.create){
Object.create = function(Person.prototype){
function F(){}
F.prototype = Person.prototype
return new F()
}
}
Child.prototype = Object.create(Person.prototype)
// 相当于 Child.prototype 是Person.prototype 它new出来的
var c = new Child('lili',12)
//继承的原型链:
//c -> Child.prototype -> Person.prototype -> Object.prototype -> null
c.run; // 访问的是Person.prototype上的run方法
function extend(o1,o2){
for(key in o2){
if(o2.hasOwnProperty(key)){
o1[key]=o2[key]
}
}
}
var o1 = {
name:'tom',
sing:function(){
console.log(this.name +'can sing !')
}
}
var o2 = {
name:'lily',
jump:function(){
console.log(this.name +'can jump high !')
}
}
extend(o1,o2)
o1.jump()
// lilycan jump high !而不是tomcan jump high !
function Child(name,age,gender){
this.parent = Person
this.parent(name,age)
delete this.parent
this.gender = gender
}
var c = new Child('meimei',20,'femail')
console.log(c)
//{name:'meimei',age:20,gender:'femail'}
function Child(name,age){
Person.call(this,name,age)
//或者 Person.apply(this,arguments)
}
Child.prototype = new Person()
var c = new Child('qq','sweet')
c.run();//qq can run !
//原型链继承:
// c -> Child.prototype -> Person.prototype -> Object -> null