js原型的初步理解(一)

<script>
        //提取方法,節省內存空間,解決數據共享問題,但是這種寫法會產生命名衝突
        function myPlay(){
            console.log("打王者榮耀");
        }  
        function Person(name,age){
            this.name=name;
            this.age=age;
            //普通寫法
            this.eat=function(){
                console.log("喜歡喫土豆");
            }
            this.myPlay=myPlay; //方法提取出去
        }

        // 通過原型來添加方法1,解決數據共享問題,節省內存空間,且能避免命名衝突問題
        Person.prototype.myHabit=function(){
            console.log('喜歡讀論語');
        }    
        //通過原型添加方法2,簡單寫法
        Person.prototype={
        //此處必須手動修改構造器的指向
        	constructor:Person,
        	height:"180cm",
            myWork:function(){
                console.log('喜歡程序員'); 
            },
            mySport:function(){
                console.log('喜歡跑步'); 
            }
        }

        var per1 = new Person('小白',20);
        var per2 =new Person('小黑',25); 
         
        console.log(per1.eat == per2.eat);  //false 此種方式會浪費內存空間,公用的方法會佔據兩個內存地址
        console.log(per1.myPlay == per2.myPlay); //true 節省內存空間,解決數據共享問題,但是這種寫法會產生命名衝突 
         
        console.log(per1.myHabit == per2.myHabit); //true ,原型寫法
        console.log(per1.myWork == per2.myWork); //true ,原型寫法
        console.log(per1.mySport == per2.mySport); //true ,原型寫法

    </script>
//原型裏面的方法可以相互引用的
function Animal(name,age){
	this.name=name;
	this.age=age;
	this.eat=function(){
		console.log(‘喫食物’);
		this.sleep();
	};
	this.sleep=function(){
		console.log('睡覺’);
		this.eat();
	}
}

//原型中添加方法
Animal.prototype.play=function(){
	console.log('玩骨頭’);
	this.walk();
}
Animal.prototype.walk=function(){
	console.log('喜歡滾泥巴’);
	this.sleep();
}

var dog=new Animal('來福',2);

//實例對象的方法是可以相互調用的
dog.eat(); 

//原型裏面的方法是可以相互調用的
dog.play();


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章