使用prototype实现继承
function Parent() {
this.name = 'parent';
}
function Son() {
}
function inherit(Son, Parent) {
Son.prototype = Parent.prototype
}
此时初步实现了Son继承Parent
如果我们现在想要为此后Son创建的实例添加一个属性firstname=‘wang’;
Son.prototype.firstname=‘wang’;
此时会发现Parent.firstname打印出也为wang
这是由于js中的引用类型的赋值是内存空间的赋值导致的(浅拷贝)
所以需要有一个中间层 F 空函数,使得Son有自己的原型属性且不会污染Parent的原型属性
圣杯模式
var inherit = (function () {
var F = function () { };
return function (Target, Orign) {
F.prototype = Orign.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Orign;
}
})();
使用extends实现继承
export default class {
params = {};
set(key, value) {
this.params[key] = value;
return this;
}
done () {
const headers = new Header();
fetch( `/api?params=${encodeURIComponent(JSON.stringify(this.params))}` , {
method: "GET",
mode: "cors",
credentials: "include",
headers
});
}
}
//继承并覆盖done方法
const temp = new class extends access {
done() {
const headers = {
'Accept': 'application:/json',
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
};
fetch( `/api?params=${encodeURIComponent(JSON.stringify(this.params))}` , {
method: "GET",
mode: "cors",
credentials: "include",
headers
});
}
}();