JS中類的概念
類,實(shí)際上就是一個(gè)function,同時(shí)也是這個(gè)類的構(gòu)造方法,new創(chuàng)建該類的實(shí)例,new出的對(duì)象有屬性有方法。
方法也是一種特殊的對(duì)象。
類的方法
在構(gòu)造方法中初始化實(shí)例的方法(就是在構(gòu)造方法中直接編寫方法,并new實(shí)例化)是不推薦的,消耗內(nèi)存(每次實(shí)例化的時(shí)候都是重復(fù)的內(nèi)容,多占用一些內(nèi)存,既不環(huán)保,也缺乏效率)。
所有實(shí)例是共有的,創(chuàng)建多個(gè)實(shí)例不會(huì)產(chǎn)生新的function,推薦在類的prototype中定義實(shí)例的方法,
prototype中的方法會(huì)被所有實(shí)例公用。
1. 仿照jQuery封裝類
匿名函數(shù)
(function () {
? ? //})();varId =function (i) {
? this.id = document.getElementById(i);
};
window.$ =function (i) {
? returnnew Id(i);
};
console.log($('main'));
function Cat(name, color) {
? this.name = name;
? this.color = color;
}varcat1 =newCat('大毛', '黃色');varcat2 =newCat('二毛', '黑色');
Cat.prototype.a = 'aaa';
Cat.prototype.type = '貓科動(dòng)物';
Cat.prototype.eat =function () {
? alert('吃老鼠');
};
cat1.eat();
cat2.eat();
console.log(cat1.name);
console.log(cat2.color);// cat1和cat2會(huì)自動(dòng)含有一個(gè)constructor屬性,指向它們的構(gòu)造函數(shù)。console.log(cat1.constructor == Cat);
console.log(cat2.constructor == Cat);// Javascript還提供了一個(gè)instanceof運(yùn)算符,驗(yàn)證原型對(duì)象與實(shí)例對(duì)象之間的關(guān)系。console.log(cat1instanceof Cat);try {
? console.log(a instanceof Cat);
} catch (e) {
? console.log(e);
}
所謂"構(gòu)造函數(shù)",其實(shí)就是一個(gè)普通函數(shù),但是內(nèi)部使用了this變量。對(duì)構(gòu)造函數(shù)使用new運(yùn)算符,就能生成實(shí)例,并且this變量會(huì)綁定在實(shí)例對(duì)象上。
Javascript規(guī)定,每一個(gè)構(gòu)造函數(shù)都有一個(gè)prototype屬性,指向另一個(gè)對(duì)象。這個(gè)對(duì)象的所有屬性和方法,都會(huì)被構(gòu)造函數(shù)的實(shí)例繼承。
prototype模式的驗(yàn)證方法
1. isPrototypeOf() 判斷某個(gè)prototype對(duì)象和某個(gè)實(shí)例之間的關(guān)系
2. hasOwnProperty() 判斷一個(gè)屬性是本地屬性還是繼承自prototype對(duì)象的屬性
3. in 判斷是否在某個(gè)對(duì)象里
function Cat(name, color) {
? this.name = name;
? this.color = color;
}
Cat.prototype.type = '貓科動(dòng)物';varcat1 =newCat('大毛', '黃色');varcat2 =newCat('二毛', '黑色');
console.log(Cat.prototype.isPrototypeOf(cat1));
console.log(Cat.prototype.isPrototypeOf(cat2));
console.log(cat1.hasOwnProperty('name'));
console.log(cat2.hasOwnProperty('type'));
console.log('name'in cat1);