JS 手写代码题目总结
日期:2021-06-27 14:00:00
更新:2021-06-27 14:00:00
标签:前端, Javascript
分类:Javascript
JavaScript 手写代码题目总结

1. 模拟一个new操作符
function MyNew() {
let obj = new Object();
let fun = Array.prototype.shift.call(arguments);
obj.__proto__ = fun.prototype;
const result = fun.apply(obj, arguments);
return typeof result === "object" ? result : obj;
}
function Test(a, b) {
this.a = a;
this.b = b;
}
Test.prototype.getA = function () {
return this.a;
};
Test.prototype.getB = function () {
return this.b;
};
var test = MyNew(Test, 1, 2);
console.log(test.getA());
console.log(test.getB());
继承
1.原型链继承
function Parent() {
this.parentA = [];
}
Parent.prototype.getParentA = function () {
return this.parentA;
};
Parent.prototype.setParentA = function (val) {
this.parentA.push(val);
};
function Child() {}
Child.prototype = new Parent();
var extendChildA = new Child();
var extendChildB = new Child();
extendChildA.setParentA("AA");
console.log(extendChildA.getParentA());
console.log(extendChildB.getParentA());
2.经典继承
function Parent() {
this.parentA = [];
}
function Child() {
Parent.call(this);
}
Child.prototype.setParentA = function (val) {
this.parentA.push(val);
};
Child.prototype.getParentA = function () {
return this.parentA;
};
var childA = new Child();
var childB = new Child();
childA.setParentA("AA");
console.log(childA.getParentA());
console.log(childB.getParentA());
3.组合继承
组合继承就是原型链继承和经典继承的组合
function Parent() {
this.arr = [];
}
Parent.prototype.setArr = function (val) {
this.arr.push(val);
};
Parent.prototype.getArr = function () {
return this.arr;
};
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var childA = new Child();
var childB = new Child();
childA.setArr("hello");
console.log(childA.getArr());
console.log(childB.getArr());
4.原型式继承
function createObj(obj) {
var Fun = function () {};
fun.prototype = obj;
return new Fun();
}
5.寄生继承
function extendObj(obj) {
var data = Object.create(obj);
data.getArr = function () {
return this.Arr;
};
return data;
}
var child = new extendObj({ Arr: ["AA"] });
console.log(child.getArr());
6.寄生组合继承
function tmpObj(obj) {
var Fun = function () {};
Fun.prototype = obj;
return new Fun();
}
function Ext(child, parent) {
var prototype = tmpObj(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
function Parent() {}
Parent.prototype.getData = function () {
return this.data;
};
function Child() {
this.data = "AA";
}
Ext(Child, Parent);
var child = new Child();
console.log(child.getData());
call,bind,apply
1.bind