function DetectorBase() {
throw new Error('Abstract class can not be invoked directly!');
}
DetectorBase.detect = function() {
console.log('Detection starting...');
}
DetectorBase.stop = function() {
console.log('Detection stopped.');
};
DetectorBase.init = function() {
throw new Error('Error');
}
//var d = new DetectorBase();// Uncaught Error: Abstract class can not be invoked directly!
function LinkDetector() {}
LinkDetector.prototype = Object.create(DetectorBase.prototype);
LinkDetector.prototype.constructor = LinkDetector;
var l = new LinkDetector();
console.log(l); //LinkDetector {}__proto__: LinkDetector
l.detect(); //Uncaught TypeError: l.detect is not a function
l.init(); //Uncaught TypeError: l.init is not a function主要是倒数第二行代码。为什么会报错,这里不是应该执行的吗?控制台应该输出 Detection starting... 吗?
---
我把老师的代码补全,实例化,调用了一下,为什么没有成功呢?
你上面给DetectorBase.detect = func.....
只是给DetectorBase这个function对象赋予了 方法,而不是给DetectorBase(或者说是子类的实例)的实例赋予了方法,如果想给实例赋予方法 必须写成 DetectorBase.prototype.detect = function......
你上面的赋值方法,仅仅是给 DetectorBase这一个function对象添加了方法,记住 实例化 的对象 的__proto__属性是指向 所属类 的 prototype 属性,要想给所有的 实例对象添加方法,就必须给所属类的原型链添加方法