面向對象類

類與實例

1:類的聲明
	1:第一種方式 用構造函數模擬類的方式 
		function Animal() {  this.name = 'name'}
	2: 第二種方式 ES6 class 
		class Animal2 {   constructor(name) {  this.name = 'name';  } }
2:生成實例
	new Animal(), new Animal2()

類與繼承

如何實現繼承
	1: 藉助構造函數實現繼承
		function Parent1() {
          this.name = 'parent1';
		}

		function Child1() {
    		Parent1.call(this); //apply
    		this.type = 'child1';
		}
		console.log(new Child1())
		 改變Parent1運行時刻this指向 Parent1 原型鏈上的東西並沒有被Child1 繼承
	
	2: 藉助原型鏈實現繼承
		function Parent2(){
   			this.name = 'parent2';
		}

		function  Child2() {
    		this.type = 'child2';
		}
		Child2.prototype = new Parent2();
		var child2 = new Child2() 
		console.log(child2);

	3: 組合繼承方式一
		function Parent4() {
   			 this.name = 'parent4';
    		 this.play = [1,2,4];
		}
		function Child4() {
 		   Parent4.call(this);
 		   this.type = 'child4'
		}
		// Child4.prototype = new Parent4()

		Child4.prototype = Parent4.prototype;
		var child41 = new Child4();
		var child42 = new Child4();
		child41.play.push(5)
		console.log(child41,child42)

	4: 組合繼承方式二
			
	 function Parent5() {
   			 this.name = 'parent5';
  			  this.play = [1,2,5];
	}
	function Child5() {
  	  Parent5.call(this);
  	  this.type = 'child5'
	}

	// Child5.prototype = Parent5.prototype;

	Child5.prototype =Object.create(Parent5.prototype);
	Child5.prototype.constructor = Child5;
	var child51 = new Child5();
	var child52 = new Child5();
	child51.play.push(5)
	console.log(child51,child52)
	 //備註 Child5.prototype.constructor = Child5;Child5.prototype =Object.create(Parent5.prototype);
繼承的幾種方式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章