這兩天在看js繼承方面,它不像OC那種傳統(tǒng)的類繼承。js繼承方式還是挺多的。比如:原型繼承、原型冒充、復(fù)制繼承
原型繼承
原型繼承有點繞,js似乎沒有類的概念,構(gòu)造對象都是用的函數(shù)調(diào)用來實例化一個對象。函數(shù)都有一個prototype屬性,如果要繼承可以用函數(shù)的prototype屬性來賦值父類的一個實例,這樣就擁有父類的屬性和方法
<script>
function Cat () {
this.climb = function () {
alert("爬樹");
}
}
function Tiger() {
this.eat = function () {
alert("吃肉");
}
}
function Animal() {
this.breath = function () {
alert("呼吸");
}
}
Tiger.prototype = new Cat();
var tiger = new Tiger();
tiger.eat();
tiger.climb();
console.log(tiger.__proto__);
console.log(tiger.__proto__.__proto__);
console.log(tiger.__proto__.__proto__.__proto__);
console.log(tiger.__proto__.__proto__.__proto__.__proto__);
var ani = new Animal();
console.log(ani.__proto__);
Tiger.prototype = ani;
tiger = new Tiger();
tiger.breath();
tiger.eat();
function All() {
this.say = function () {
alert("say");
}
}
Animal.prototype = new All();
ani = new Animal();
ani.say();
</script>
原型冒充
注意call的用法
<script>
function Good() {
this.goodStudy = function () {
console.log("好好學(xué)習(xí)");
console.log(this);
}
}
function Bad() {
Good.call(this);
this.badPlay = function () {
console.log("就會玩");
}
}
var bad = new Bad();
bad.badPlay();
bad.goodStudy();
</script>
復(fù)制繼承
<script>
function Good() {
this.iq = 120;
this.goodStudy = function () {
console.log("好好學(xué)習(xí)");
}
}
function Bad(obj) {
this.badPlay = function () {
console.log("就會玩");
}
this.extend = function (obj) {
for (var k in obj){
this[k] = obj[k];
}
}
}
var good = new Good();
var bad = new Bad();
bad.extend(good);
bad.goodStudy();
console.log(bad.iq);
</script>
這里面遇到一個問題,在循環(huán)遍歷extend函數(shù)的時候,訪問對象屬性用的“[ ]”,如果用“.”會報錯,其實js對象屬性有兩種訪問形式:“.”和“[ ]",兩個有區(qū)別,性能方面“.”更高一些。
Obj.key 和 Obj[key] 我的通俗理解: 1、當(dāng)對象的屬性key不確定而是一個變量的時候必須使用[] 2、[]里可以是任意字符串,而. 不能隨便 3、使用. 號key可不加引號, 使用[] key有時候需要加引號。
嗯,就寫到這里