一、原型鏈繼承(prototype)html
<!DOCTYPE html> <html> <body> <script> function A(name){ this.name = name; this.sleep = function(){ console.log(this.name+"正在睡覺..."); } this.eat = function(food){ console.log(this.name+"正在吃:"+food); } } function C(name){ this.name = name; } C.prototype = new A(); var c = new C("Toms"); console.log(c.name); //Toms console.log(c.eat('水果')); //Toms正在吃:水果 console.log(c.sleep()); //Toms正在睡覺... </script> </body> </html>
建立一個A類,給它一個名字屬性,一個睡覺的方法,一個吃的方法函數
建立一個C類,給它一個名字屬性this
利用prototype確立繼承關係,可是這種方法有個缺點,new出來的對象會大量的佔內存空間,因此使用另外一種方法Object.create來確立繼承關係spa
function Parent(){}
Parent.prototype.age = 18;
function Child(){}
Child.prototype = Object.create(Parent.prototype); //肯定繼承關係
Child.prototype.constructor = Child;//改回原來對象(Child)的構造器
//只要某個構造器的prototype改變,新new出的對象的構造器也會改變
Child.prototype.cno = "01";
var p = new Parent();
var c = new Child();
console.log(c.age);
2.構造繼承(call)prototype
//*********call的理解********* //this指向誰是由運行時決定 //this等於.號左邊的東西 function P(name,age){ this.name = name; this.age = age; } var o = {}; P.call(o,"a",18); //此時P函數裏面的this等於第一個參數 console.log(o.name); console.log(o.age);
<!DOCTYPE html> <html> <body> <script> function A(name){ this.name = name; this.sleep = function(){ console.log(this.name+"正在睡覺..."); } this.eat = function(food){ console.log(this.name+"正在吃:"+food); } } function B(name){ A.call(this); this.name = name; } var b = new B("Lucy"); console.log(b.name); //Lucy console.log(b.eat('零食')); //Lucy正在吃:零食 console.log(b.sleep()); //Lucy正在睡覺... </script> </body> </html>
總得來講JS裏的類就是構造器+原型htm
且constructor構造器通常指向函數。對象