// 先看下原型继承的实现方式
function Parent() {
this.name = 'zhang san'
}
Parent.prototype.getName = function() {
console.log(this.name)
}
function Child() {
}
Child.prototype = new Parent()
var child1 = new Child()
child1.getName() // zhang san
Child.prototype 是Parent的实例化子对象
Child 构造函数就拥有了 this.name = 'zhang san ' 和
getName 方法
child1 是Child的实例化子对象, 故能继承Child 的属性和方法
// 下面是构造函数继承
function Parent () {
this.name =['jony', 'tom']
}
Parent.prototype.getName = function() {
console.log (this.name)
}
function Child () {
Parent.call(this)
// 此处借助call 来用Parent的方法和属性
// 补充: apply 和call 的区别, apply(this, [arr]) , 第二个参数是数组形式 call 的第二个参数是单个值.
}
var child1 = new Child()
child1.name.push('lily')
console.log(child1.name) //["jony", "tom", "lily"]
var child2 = new Child()
console.log(child2.name) // ) ["jony", "tom"]
1,prototype可以动态的给对象增加属性和方法
2,可以实现子类继承父类,拥有父类的属性和方法
3,call和apply的区别,在于参数。
4,call和apply,可以肤浅理解为在子运行环境中执行父类的方法和属性。
5,call和apply可以实现多继承,一个子类可以继承多个父类,但是prototype只能有有一个父类**
网友评论