函数中的this指向
谁调用这个函数 this就指向谁,没有就是window
匿名函数在非严格模式下被window调用
关于原型见 原型 原型链
https://juejin.im/post/59bfe84351882531b730bac2#heading-9
apply/call/bind
劫持另一个对象并继承他的属性,可以改变this指向
apply的第一个参数是改变this指向的对象, 第二个是形参数组
call的第一个之后的参数是每一个形参
bind会新建一个函数,必须手动调用。用法是a.bind(b, 1, 2)()
apply妙用
Math.max.apply(null,arr) 不循环数组求最大/小值
Array.prototype.push.apply(arr1,arr2) 合并两个数组(类似concat但会改变第一个数组的值)
https://www.jianshu.com/p/4d17f1b147fc
https://www.cnblogs.com/xiaohongwu/archive/2011/06/15/2081237.html
手写call apply bind
Function.pototype._call = function () { // _call 需要写在function的原型上
const ctx = arguments[0] || window; // 传入的第一个参数决定this指向谁,没有参数则指向window
let fn = Symbol(); // es6用法 避免函数fn重名
ctx.fn = this; // 将执行的函数赋值给改变指向的对象(ctx)的属性(fn)
// let args = [].shift.call(arguments); // 取其它参数
let args = []; // 取其它参数
for (let i = 1; i < arguments.length; i++) { // apply的话第二个参数是数组,取arguments[1]
args.push(arguments[i]);
}
// 执行已经改变this指向的对象上的方法并传参
let res = ctx.fn(...args);
// _bind返回一个函数
// let res = function () {
// ctx.fn(...args);
//}
// 删除这个方法
delete ctx.fn;
// 将结果返回
return res;
}
https://www.jianshu.com/p/08238efc6a9b
https://www.jianshu.com/p/4bf613cb393e
https://www.cnblogs.com/620chang/p/12699102.html