// 不使用Object.create()
// method1:
function Parent(){
this.name = 'xiaohong'
this.list = [1,2,3]
}
Parent.prototype.sayHi = function(x) {
console.log('Hi')
}
function Child(){
this.type = 'Child'
}
Child.prototype = new Parent()
let child1 = new Child()
let child2 = new Child()
child1.name = 'xiaoming'
console.log(child1.name,child2.name) // xiaoming,xiaohong
child1.list.push(4)
console.log(child1.list,child2.list) // [1,2,3,4],[1,2,3,4]
// 问题:子类实例对象的引用数据类型之间会互相引用
// method2:
function Parent(){
this.name = 'xiaohong'
this.list = [1,2,3]
}
Parent.prototype.sayHi = function(x) {
console.log('Hi')
}
function Child(){
Parent.call(this)
this.type = 'Child'
}
let child1 = new Child()
child1.sayHi() // 无法调用
// method3:
function Parent(){
this.name = 'xiaohong'
this.list = [1,2,3]
}
Parent.prototype.sayHi = function(x) {
console.log('Hi')
}
function Child(){
Parent.call(this)
this.type = 'Child'
}
Child.prototype = new Parent()
Child.prototype.constructor = Child
// 可以正常使用,但是Parent执行了两次,加大了性能的开销
// 使用Object.create()
// method4:
function Parent(){
this.name = 'xiaohong'
this.list = [1,2,3]
}
Parent.prototype.sayHi = function(x) {
console.log('Hi')
}
let child1 = Object.create(Parent)
let child2 = Object.create(Parent)
child1.list.push(4)
child2.list.push(4)
console.log(child1.list) //[1,2,3,4,4]
// Object.create是浅拷贝,会导致互相引用
// method5:
function Parent(){
this.name = 'xiaohong'
this.list = [1,2,3]
}
Parent.prototype.sayHi = function(x) {
console.log('Hi')
}
function clone(parent){
let child = Object.create(parent)
child.prototype.method = function(){
//.....
}
}
let child = clone(Parent)
// 不足之处和上面一样,浅拷贝
// method5:
function Parent(){
this.name = 'xiaohong'
this.list = [1,2,3]
}
Parent.prototype.sayHi = function(x) {
console.log('Hi')
}
function clone(parent){
let child = Object.create(parent)
child.prototype.method = function(){
//.....
}
}
let child = clone(Parent)
// 不足之处和上面一样,浅拷贝
// method6
function Parent(){
this.name = 'xiaohong'
this.list = [1,2,3]
}
Parent.prototype.sayHi = function(x) {
console.log('Hi')
}
function Child(){
Parent.call(this)
this.name = 'Child'
}
Child.prototype = Object.create(parent.prototype) //使用Object.create,避免实例创建
Child.prototype.constructor = Child
Child.prototype.sayName = function(){}
// 最完美的方法