javascript继承6种方法

	function Animal(){
        this.species = "动物";
      }
	Animal.prototype.species = "动物";

      function Cat(name,color){
        this.name = name;
        this.color = color;
      }
	
//	1.构造函数绑定
	function Cat(name,color){
//		这里this是Cat,arguments是传进来的实参
		Animal.call(this,arguments);
        this.name = name;
        this.color = color;		
	}
	var cat = new Cat('短毛','黑色');
	console.log(cat.species);
	
//	2.prototype模式
//	我们将Cat的prototype对象指向一个Animal的实例。它相当于完全删除了prototype 对象原先的值,然后赋予一个新值。
	Cat.prototype = new Animal();
//	任何一个prototype对象都有一个constructor属性,指向它的构造函数。
//	如果没有"Cat.prototype = new Animal();"这一行,
//	Cat.prototype.constructor是指向Cat的;加了这一行以后,Cat.prototype.constructor指向Animal。
	Cat.prototype.constructor = Cat;
	var cat2 = new Cat('长毛','白色');
	console.log(cat2.species)
	
//	3.直接继承prototype
	Cat.prototype = Animal.prototype;
	Cat.prototype.constructor = Cat;
	var cat3 = new Cat('细毛','蓝色');
	console.log(cat3.species)
	
//	4.空对象继承prototype
	function extend(Child,Parent){
		function F(){}
		F.prototype = Parent.prototype;
		Child.prototype = new F();
		Child.prototype.constructor = Child;
	}
	extend(Cat,Animal)
	var cat4 = new Cat('粗毛','紫色');
	console.log(cat4.species)
	
//	5.拷贝继承
	function extend2(Child,Parent){
		var c = Child.prototype;
		var p = Parent.prototype;
		
		for (var i in p) {
			c[i] = p[i];
		}
	}
	extend2(Cat,Animal);
	var cat5 =  new Cat('羊毛','黄色');
	
// 6.类继承
class Animal{
		constructor(name,age){
			this.name = name;
			this.age = age;
		}
		eat(){
			console.log('吃吃吃!');
		}
		run(){
			console.log('跑跑跑!');
		}
	}
	class Dog extends Animal{
		constructor(name,age,cry){
			super(name,age);
			this.cry = cry;
		}
	}
	
	var dog = new Dog('加菲猫',3,'喵喵喵');
	dog.eat()

console.log(cat5.species)

猜你喜欢

转载自blog.csdn.net/qq_36245035/article/details/80749902