Open dave-wind opened 1 year ago
Function.prototype._bind = function(ctx,...args) {
const self = this; // 谁调用 就是指向谁
return function(){
// self.call(self,...args)
// 如果有返回值 需要return出去
return self.call(self,...args)
}
}
eg:
const obj = {
name: 'dave',
show() {
console.log(this.name)
}
}
const obj2 = { name: 'wind' };
var a= obj.show.bind(obj2);
a(); // wind
function A() { }
var a1 = new A();
function _instanceof(target, Fn) {
if ((typeof target !== 'object' && typeof target !== 'function') || target == undefined) {
return false
}
let proto = target.__proto__;
// 层层往上找
while (true) {
if (proto === null) return false
if (proto === Fn.prototype) {
return true
}
// 如果不是,继续向上找
proto = proto.__proto__;
}
}
console.log("A----", _instanceof(a1, A));
Array.prototype._map = function (exec) {
const result = [];
for (let i = 0; i < this.length; i++) {
result[i] = exec(this[i], i, this)
}
return result;
}
const a2 = new Array(5).fill(1)
console.log(a2, a2._map((itm, index) => itm * index + 1)) // [1,2,3,4,5]
Object.prototype._create = function (proto) {
const Fn = function () { }
Fn.prototype = proto
return new Fn()
}
function A() { }
const obj = Object.create(A)
const obj2 = Object._create(A)
console.log(obj.__proto__ === A) // true
console.log(obj.__proto__ === A) // true
Array.prototype._filter = function (fn) {
let result = [];
for (let i = 0; i < this.length; i++) {
// 过滤执行结果
if (fn(this[i], i, this)) {
result.push(this[i])
}
}
return result
}
const b = [1, 3, 4, 5, 6, 2, 5, 1, 8, 20]
console.log(b._filter(item => item % 2 === 0)); // [ 4, 6, 2, 8, 20 ]
console.log(sum(1, 2)(3)()) // 6
console.log(sum(1)(2)(3)()) // 6
console.log(sum(1, 2, 4)(4)()) // 11
function sum(...args) {
let params = args;
const fn = (...newArgs) => {
// 没有参数时候 直接执行
if (newArgs.length == 0) {
return params.reduce((pre, cur) => pre + cur, 0)
} else {
params = [...params, ...newArgs]; // 收集过程
return fn
}
}
return fn;
}
sum(1)(2)(3)() // 6
模拟实现 new 关键字功能