//类的创建
//1.成员变量(构造器方式)
function ClassA(sName){
this.name = sName;
}
//2.成员函数(原型方式)
ClassA.prototype.showName = function(){
console.log('name is ' + this.name);
}
//对象的创建,使用new关键字
var ca = new ClassA('Jean');
ca.showName();//name is Jean
//类的继承
//1.成员变量(call或者apply)
function ClassB(sName, iAge){
ClassA.call(this, sName);
this.age = iAge;
}
//2.成员函数(将new ClassA()赋值给prototype)
ClassB.prototype = new ClassA();
ClassB.prototype.showInfo = function(){
console.log(this.name + '\'s age is ' + this.age);
};
var cb = new ClassB('Billy', 21);
cb.showName();//name is Billy
cb.showInfo();//Billy's age is 21
console.log('cb instanceof ClassA: ' + (cb instanceof ClassA));//cb instanceof ClassA: true
console.log('cb instanceof ClassB: ' + (cb instanceof ClassB));//cb instanceof ClassB: true
[javascript]js中类的创建和继承
最新推荐文章于 2022-12-19 23:11:43 发布