js方法繼承

  仍是原來的味道,原來的配方,咱們先來了解你這讓你登上山頂的板磚(有些是我的想法和方法)html

第一步、咱們須要知道的是你定義的方法都會有一個prototype(用來存放公共的屬性和方法),而這個原型指向一個原型對象.原型對象中又存在constructor和__proto__、方法(如圖一)node

                                  圖一數組

  第二步、你須要知道實例化(new)後會產生一個__proto__(能夠理解爲__proto__取代了prototype的位置並指向了原型對象),如圖二app

<script>
function a(){

}
var b=new a()
console.log([a],[b])
console.log(a.prototype===b.__proto__)
</script>

  

                                圖二this

  第三步、如今咱們在瞭解基本知識的狀況下開始正式介紹方法繼承(你想獲得誰的方法就指向誰)prototype

    一、原型繼承(指向原型對象,指向原型對象後此原型對象就變成用來存放兩人的方法了)Man.prototype = Person.prototype(將Man的原型指向Person的原型,原型變成公有的了);3d

      

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	
</body>
</html>
<script>
//人類
function Person(name,age,sex){
	this.name = name;
	this.age = age;
	this.sex= sex;	
}
Person.prototype.sleep = function(){}
Person.prototype.play = function(){}
Person.prototype.eat = function(){}
		
function Man(beard,larynx,name,age,sex){

	Person.apply(this,[name,age,sex])
	this.beard = beard;
	this.larynx = larynx;
}

/*
	污染父級

 */
Man.prototype = Person.prototype


Man.prototype.work = function(){}


//實例化
var chenliang = new Man(10,"很大","阿狗","40","男");
console.log(chenliang)
console.log([Man],[Person])
</script>

  結果如圖三htm

  

  從圖中咱們不難看除Man和Person原型中的方法時同樣的,也能夠得出其最大的缺點就是污染"父級".對象

  二、爲了解決污染父級的問題咱們就不能讓子集的原型指向父級的原型,如今咱們來觀察一下方法中還有哪些屬性,這個時候咱們發現了arguments(僞數組(nodelist),也能夠稱它爲對象),//方法的名字尚未想好讀者能夠提喔!blog

  

Man.prototype.arguments=Person.prototype;在Man.prototype建立一個arguments,再把Person.prototype的方法放入

  

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	
</body>
</html>
<script>
		//人類
function Person(name,age,sex){
	this.name = name;
	this.age = age;
	this.sex= sex;
}


Person.prototype.sleep = function(){}
Person.prototype.play = function(a){
	console.log(a,'你好')
}
Person.prototype.eat = function(){
	console.log("1122")
}
		

function Man(beard,larynx,name,age,sex){

	Person.apply(this,[name,age,sex])
	this.beard = beard;
	this.larynx = larynx;
}

Man.prototype.arguments=Person.prototype;



Man.prototype.work = function(){}


//實例化
var chenliang = new Man(10,"很大","陳亮","40","男");
chenliang.arguments.play(1);
console.log([Man])






</script>

  結果如題四

  

                            圖四

其餘的繼承方式之後補上.

相關文章
相關標籤/搜索