ECMAScript 继承机制实现问题

半夏情 半夏情 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
当我使用混合方式定义“类”ClassA时;使用对象冒充方式ClassB继承ClassA,为何报错原型函数未定义;
function ClassA(sColor){
this.color = sColor;
/*this.sayColor = function(){
console.log(this.color);
}*/ //这种构造方式是可以的
}

//原型方法
ClassA.prototype.sayColor = function(){
console.log(this.color);
}

function ClassB(sColor,sName){
this.newMethod = ClassA;//函数名只是指向它的指针
this.newMethod(sColor);//调用(复制);
delete this.newMethod;
//所有新属性和新方法都必须在删除了新方法的代码行后定义。否则,可能会覆盖超类的相关属性和方法:
this.name = sName;
}
ClassB.prototype.sayName = function(){
console.log(this.name);
}
var objA = new ClassA("red");
objA.sayColor();
var objB = new ClassB("blue","Bill");
objB.sayName();
objB.sayColor();//这里有问题
报错如下:
objB.sayColor is not a function
at Object.
...全文
评论 3
收藏 已收藏
分享
返回顶部
半夏情
JavaScript 87,983 成员 224,681 内容