JS中類的概念
類,實際上就是一個function,同時也是這個類的構造方法,new創建該類的實例,new出的對象有屬性有方法。
方法也是一種特殊的對象。
類的方法
在構造方法中初始化實例的方法(就是在構造方法中直接編寫方法,並new實例化)是不推薦的,消耗內存(每次實例化的時候都是重復的內容,多占用一些內存,既不環保,也缺乏效率)。
所有實例是共有的,創建多個實例不會產生新的function,推薦在類的prototype中定義實例的方法,
prototype中的方法會被所有實例公用。
1. 仿照jQuery封裝類
匿名函數
(function () {
//
})();
var Id = function (i) {
this.id = document.getElementById(i);
};
window.$ = function (i) {
return new Id(i);
};
console.log($('main'));
function Cat(name, color) {
this.name = name;
this.color = color;
}
var cat1 = new Cat('大毛', '黃色');
var cat2 = new Cat('二毛', '黑色');
Cat.prototype.a = 'aaa';
Cat.prototype.type = '貓科動物';
Cat.prototype.eat = function () {
alert('吃老鼠');
};
cat1.eat();
cat2.eat();
console.log(cat1.name);
console.log(cat2.color);
// cat1和cat2會自動含有一個constructor屬性,指向它們的構造函數。
console.log(cat1.constructor == Cat);
console.log(cat2.constructor == Cat);
// Javascript還提供了一個instanceof運算符,驗證原型對象與實例對象之間的關系。
console.log(cat1 instanceof Cat);
try {
console.log(a instanceof Cat);
} catch (e) {
console.log(e);
}
所謂"構造函數",其實就是一個普通函數,但是內部使用了this變量。對構造函數使用new運算符,就能生成實例,並且this變量會綁定在實例對象上。
Javascript規定,每一個構造函數都有一個prototype屬性,指向另一個對象。這個對象的所有屬性和方法,都會被構造函數的實例繼承。
prototype模式的驗證方法
1. isPrototypeOf() 判斷某個prototype對象和某個實例之間的關系
2. hasOwnProperty() 判斷一個屬性是本地屬性還是繼承自prototype對象的屬性
3. in 判斷是否在某個對象里
function Cat(name, color) {
this.name = name;
this.color = color;
}
Cat.prototype.type = '貓科動物';
var cat1 = new Cat('大毛', '黃色');
var cat2 = new Cat('二毛', '黑色');
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);
console.log('type' in cat1);
未完:構造函數的繼承:http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance.html
非構造函數的繼承:http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance_continued.html

