this是运行时才确定,用来改变this的指向
执行函数并绑定参数
之前一篇文章通过数组边遍历边删除来回顾迭代器附录中描述了一遍this与箭头函数的几种情况
当this是null、undefined时,默认指向window
箭头函数无arguments 对象,用 Rest 参数代替
简述
call(‘绑定this’,’参数’,’列表’) 立即调用
apply(‘绑定this’,[‘参数’,’数组’]) 立即调用
bind(‘绑定this’,’参数’,’列表’) 返回函数需要再次调用
应用场景
1 2 3 4 5 6 7 8 9 10 11 12 13
| var obj = { message: 'hello: ' } function getName(str1, str2) { console.log(this.message + str1 + ' ' + str2) } getName.call(obj, 'a', 'b') getName.apply(obj, ['a', 'b'])
var arr = [1, 2, 3, 89, 46] var max = Math.max.call(null,arr[0],arr[1],arr[2]) var max = Math.max.apply(null,arr)
|
1 2 3 4 5 6 7 8 9 10 11 12
| var trueArr = Array.prototype.slice.call(arrayLike);
var total = [].push.apply(arr1, arr2);
Object.prototype.toString.call(obj)
function log(){ console.log.apply(console, arguments); }
var log = console.log()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| var Person1 = function(){ this.name = 'Dot'; } var Person2 = function(){ this.getname = function(){ console.log(this.name); } Person1.call(this); } var Person3 = function(){ Person1.apply(this,arguments) } var person = new Person2(); person.getname();
|
1 2 3 4 5 6 7 8 9 10 11
| var add = function(x) { return function(y) { return x + y; }; };
var increment = add(1); var addTen = add(10); increment(2); addTen(2);
|
1 2 3 4 5 6 7 8 9 10 11
| if (!Function.prototype.bind) { Function.prototype.bind = function () { var self = this, context = [].shift.call(arguments), args = [].slice.call(arguments); return function () { self.apply(context, [].concat.call(args, [].slice.call(arguments))); } } }
|
文章题目也不好取啊- -想起之前有本工具手册《MySQL必知必会》,那就用你好了
附录1 this
我们再来看看this的更多例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| function a1(){ console.log(this) } var obj = { a1:()=>{ console.log(this) }, a2:function(){ console.log(this) }, a3:function(){ console.log(this) } } obj.a1() obj.a2() var obja3 = obj.a3; obja3()
id.addEventListener('click',function(){ console.log(this) })
setTimeout(function(){ console.log(this); }, 200);
function Person(name,age){
this.name = name this.age = age this.getAge = () =>{ console.log(this.age) } this.getAge = function(){ console.log(this.age) } } var p = new Person('P',2) p.getAge()
|
附录2 函数执行时说明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| obj1.fn() obj1.fn.call(obj1);
fn1() fn1.call(null)
f1(f2) f1.call(null,f2)
obj1.fn() obj1.fn.apply(obj1);
fn1() fn1.apply(null)
f1(f2) f1.apply(null,f2)
|