JavaScript this指向相关内容

1,默认绑定this指向windw对象

看代码:

function test(C){

var a = 123

function b(){};

}

在预编译环节当中。

OA{

arguments:[1],

this : window,

C : 1,

A : undefined,

b : funtion(){}

}

test(1)

PS: 也就是说,在正常情况下,函数执行,this指向window;

那么有我们想改变this指向,我们该如何做到呢? 看下面

2,隐式改变:谁调用this指向谁;

看代码:

var str = '2222';

var obj = {

str:'1111',

b:function(){

console.log(this.str)

}

}

第一步:

obj.b() 会出现什么? // 11111

实现谁调用指向谁

并且我们的dome的onclick事件都是

升级: var fun = obj.b;//fun 存放了 obj.b整个函数的引用

fun() //2222

为什么?谁调用只想谁!

再看一道题:

var str = '2222';

var obj = {

str:'1111',

b:function(){

console.log(this.str)

}

}

var obj2 = {

str:'33333',

b : function(fn){

fn()

}

}

obj2.b( obj.b)// 出现什么?2222

obj2.b = obj1.b

obj2.b();//3333

讲解:

obj2.b( obj.b) 相当于obj.b作为实参传到函数里,形参接收之后,便有了obj.b的函数体引用,那么再

obj2.b里执行的过程中,fn()并没有对象调用它,只是一个单独函数体执行,内部走预编译的过程中。

从中扩展出 setTimeout(function(){ },1000)或者回掉函数也是这个原理

3,显式绑定:call apply bind

代码如下

var str = 'window';

var obj = {

str :'str',

print:function(){

console.log(this.str);

}

}

let newPrint = obj.print.bind(window);//bind 返回一个新的this指向的函数

// newPrint();

newPrint.call(obj);//bind只能绑定一次 bind过的函数 this无法在改变

// newnewPrint();

讲解,我们想主动改变this的指向,需要的方法call apply bind 。call和apply可以让函数执行,而bind可以返回一个新的函数体。bind改变this最厉害,bind之后的函数,call和apply都无法改变;

但是有一个方法可以改变this ,那就是下面的new操作符,请看下面

4 ,new 操作符

function test(C){

// var this = object.create(test.prototyoe)

// {

// __proto__:test.prototype

//}

var a = 123

function b(){};

}

new test

讲解:当new的过程中,函数内部出现// var this = object.create(test.prototyoe);使this发生改变。

总结: 四种this绑定的权重(看谁最厉害)

//1,默认绑定(空函数执行,函数单纯执行,this指向window) 默认权重

//2,隐式帮定(谁调用this指向谁) 第三权重

//3,显式绑定 (call apply bind) 第二高权重

//4,new 绑定this 权重是最高的

升级知识:ES6箭头函数中的this如何邦定?

//学习箭头函数,同学必须知道的几件事。 重要!!!!

//1,箭头函数没有this 没有arguments surper(class);

//2,箭头函数不能new ,不当成构造函数来 没有prototye;

//3,可以表示数据流向 方便JavaScript引擎优化扫码;

看代码:

var reg = 'window';

var obj1 = {

reg:"reg",

print:() => console.log(this.reg)

}

var obj2 = {

reg:"reg",

print:function(){

console.log(this.reg)

}

}

obj1.print() //window

obj2.print() //reg

讲解:箭头函数具有绑定this的能力 ,一旦箭头函数定义,this已经绑定,并且无法修改;

箭头绑定规则:绑定里最近的非箭头函数作用域中的this : 1 找到最近的非箭头的作用域 2 找this

最后再看一个例子:

var obj2 = {

reg:'obj',

getName:function(){

let show = () =>console.log(this.reg)

show();

}

}

obj2.getName() //obj

//scope2(show)----->scope1(getName) 'obj'

讲解:箭头函数show执行,找上一个非箭头函数作用域,发现是getName方法的作用域,然后找this,指向的是obj2,所以最后打印的是 ‘obj’;

原文地址:https://www.cnblogs.com/pandawind/p/9791029.html