JavaScript類的相關知識
1.例子
/* 例1 */
// 定義一個構造函數
function Range(from, to){
this.from = from;
this.to = to;
}
// 所有Range類的實例化對象都會繼承構造函數Range的prototype屬性
Range.prototype = {
toString: function(){
return this.from + '....' + this.to;
},
includes: function(x){
return x >= this.from && x <= this.to;
}
};
// 實例化一個對象
var r = new Range(1, 3);
// 因為r繼承了Range.prototype, 所以可以直接調用里面的方法
r.toString()
2.constructor屬性
/* 例2 */
// 由上圖可知
var F = function(){}; // F表示一個函數對象
var P = F.prototype; // P表示函數的原型對象
var C = P.constructor; // C表示原型對象下面的constructor屬性
// 則有
C === F;
var O = new F(); // 創建類F的實例化對象
o.constructor === F;
/*
也就是說 F.prototype.constructor 就等於構造函數本身
而 F 實例化出來的對象 O 繼承了 F.prototype 所以就
有 o.constructor === F
*/
// 在例1中,因為重寫了Range預定義的原型對象,所以Range.prototype中便不存在constructor屬性了,解決這一問題的方法有兩種
// 法一:顯示的給原型添加一個構造函數
Range.prototype = {
constructor: Range, // 顯示的設置構造函數的反向引用
toString: function(){
return this.from + '....' + this.to;
},
includes: function(x){
return x >= this.from && x <= this.to;
}
};
// 法二:使用預定義的原型對象,因為預定義的原型對象中已經包含了constructor屬性了
Range.prototype.toString = function(){
return this.from + '....' + this.to;
};
Range.prototype.includes = function(x){
return x >= this.from && x <= this.to;
};
由例1和例2可以總結出javascript中定義類的步驟:
第一步:先定義一個構造函數,並設置初始化新對象的實例屬性
第二步:給構造函數的prototype對象定義實例方法
第三步:給構造函數定義類字段和類屬性
3.繼承

/* 例3 */ function Parent(name, age){ this.name = name; this.age = age; }; Parent.prototype.say = function(){ console.log(this.name, this.age); }; // 繼承Parent類 function Child(name, age, sex){ Parent.call(this, name, age); this.sex = sex; }; // Child繼承了來自父類Parent的方法,可以繼續在自己的原型上擴展方法 Child.prototye.ask = function(){ console.log(this.name + '-----' + this.age + '-----' + this.sex); }; // child類為繼承了Parent類屬性及方法的類 var c = new Child('javascript', 18, 'male'); c.say(); c.ask();
4.新語法定義類以及及繼承類
/* 例4 */
// 定義一個Parent類
class Parent{
constructor(name, age){ // 相當於Parent.prototype.constructor
this.name = name;
this.age = age;
}
say (){ // 相當於Parent.prototype.say = function(){}
console.log(this.name, this.age);
}
};
// 定義一個Child類繼承Parent類
class Child extends Parent{
constructor(name, age, sex){
super(name, age);
this.sex = sex;
}
ask (){
super.say(); // 通過super關鍵字調用父類中的方法
}
};