this的用法
指代当前调用的这个对象:4种绑定规则分别是:默认绑定、隐士绑定、显示绑定、new绑定。优先级从低到高
var name='tom';
var obj= {
getName: function(){
console.log(this+' '+this.name);//this指向对象本身
},
getAge: function(){
//var that = this; //将此处this保留,可在局部函数使用
function aa(){
//console.log(that.name); //jack
console.log(this+ ' '+ this.name);//局部函数的this指向Window
}
aa(); //Window.aa()
}
}
obj.getName(); //[object Object] jack
obj.getAge(); //[object Window] undefined
var fn=obj.getName;
fn(); //[object Window] tom
//改变this指向
var fn1= obj.getName.bind(obj);//把this的指向绑定给obj
fn1(); //[object Object] jack
- this的作用域是调用(执行)时创建的,而不是定义时创建的 -- 也可以看做是一个改变this指向的例子
var obj = {num :12}
var obj1 = {
num : 11,
fn : function () {
return this.num
}
}
console.log(obj1.fn()); //11
obj.fun = obj1.fn;
console.log(obj.fun()); //12
- 箭头函数的this指针-- 指向定义时的上级作用域
var obj = {num :12}
var obj1 = {
num : 11,
fn: function() {
return () => {return this.num}; //箭头函数的this指向其定义时的上级作用域,这里指向obj1
}
}
var fun = obj1.fn()
console.log(fun()); //11
手写bind方法
Function.prototype.newBind = function() {
//1、arguments接收参数,并将其转化为数组(本身是类数组),
//因为最后要调用apply(),参数要以数组的形式传入
const args = Array.prototype.slice.call(arguments);
//2、弹出第一个参数(对象)
const obj = args.shift()
//fn1.bind(...)里的fn1
const self = this;
//返回一个函数
return function(){
return self.apply(obj,args);
}
}
let fn1=function(a,b,c){
console.log('this',this);
console.log(a,b,c);
return 'this is'
}
const fn2= fn1.NewBind({num: 'x'},10,20,30)
console.log(fn2());
- 构造器里的this
//通过new调用构造器来实例化一个对象,构造器中的this指向(例如func1.prototype)的空对象
//如果构造器函数没有return语句,或者return的是基本类型,将this指针指向的变量返回
function func1() {
this.a = 10;
a = 20;
return a;
}
var obj1 = new func1()
console.log(obj1.a); //10
// 如果return的是一个对象,这以对象中对应的变量返回
function func2() {
this.a = 10;
return {a: 20}
}
var obj2 = new func2();
console.log(obj2); //20
- /* 严格模式下函数的this */ --对于普通(全局)函数适用
function fn2() {
"use strict"
return this;
}
console.log(fn2()); //undefined
总结: this的不同应用场景,如何取值
- 作为普通函数被调用, this指向window
- 使用call、apply、bind, this指向被传入的参数(对象)
- 作为对象方法被调用, this指向该对象