原型的继承

//原型链继承,问题会更改引用值的改变
function Super(){
    
    
	this.a=[1,2,3,4]
}
Super.prototype.say=function(){
    
    
	console.log(2222)
}
function Sub(){
    
    
	
}
Sub.prototype=new Super();
var sub1= new Sub();
var sub2=new Sub();
 sub1.a.push(5)
//第二种方法,构造函数继承,没办法拿到原型上的方法
function Super(){
    
    
	this.a=[1,2,3,4]
}
Super.prototype.say=function(){
    
    
	console.log(2222)
}
function Sub(num){
    
    
	
	Super.call(this,num)
}
var sub1= new Sub([1,2,3,4]);
var sub2=new Sub();
 console.log(sub1)
//组合继承,使用原型链继承一次再用构造函数继承一次
function Super(){
    
    
	this.a=[1,2,3,4]
}
Super.prototype.say=function(){
    
    
	console.log(2222)
}
function Sub(){
    
    	
	Super.call(this)
}
Sub.prototype=new Super()
var sub1= new Sub();
var sub2=new Sub();
 console.log(sub1.b) 
//寄生组合继承
function Super(){
    
    
	this.a=[1,2,3,4]
}
Super.prototype.say=function(){
    
    
	console.log(2222)
}
function Sub(){
    
    	
	Super.call(this)
}
if(!Object.create){
    
    //解决兼容
	Object.create=function(proto){
    
    
		function F(){
    
    
			F.prototype=proto
			return new F();
		}
	}
}
Sub.prototype=Object.create(Super.prototype)
var sub1= new Sub();
var sub2=new Sub();
   console.log(sub1.b) 

猜你喜欢

转载自blog.csdn.net/weixin_51109349/article/details/121903487