箭头函数this指向上级作用域
let obj= {
fn:function ( ) {
console. log ( this )
return ( ) => {
console. log ( this )
}
}
}
var f = ( ) => {
cosole. log ( this )
}
f ( )
在全局作用域,this指向window;this 和window是同一块空间地址;
console. log ( this ) ;
window. alert ( )
this . alert ( ) ;
给元素的事件绑定的函数中的this,指向了当前被点击的那个元素;
box. onclick = function ( ) {
console. dir ( this === box) ;
box. style. color = "red" ;
this . style. color = "red" ;
this = 100 ;
}
看函数执行前有没有".",如果要是没有,那么函数中的this指向window,如果有"." ,那么点前面是谁,this就指向谁;
function fn ( ) {
console. log ( this ) ;
}
fn ( )
var fn = function ( ) {
console. log ( this ) ;
}
fn ( ) ;
var obj = {
m: 1 ,
fn : function ( ) {
console. log ( this ) ;
}
}
var f = obj. fn;
console. log ( f == obj. fn) ;
obj. fn ( ) ;
自执行函数中this 永远指向window;
( function ( ) {
console. log ( this ) ;
} ) ( ) ;
var obj = {
fn: ( function ( ) {
console. log ( this ) ;
return function ( ) {
console. log ( this ) ;
}
} ) ( )
}
var f = obj. fn;
f ( ) ;
let b = { }
b. f = f
b. f ( ) ;
回调函数中的this一般都指向window;
setTimeout ( function ( ) {
console. log ( this ) ;
} , 1000 ) ;
var ary= [ 1 , 2 , 3 , 4 ]
ary. map ( function ( ) {
console. log ( this ) ;
} )
function A ( ) {
console. log ( this ) ;
}
function B ( a ) {
var obj = { a: a}
obj. a ( ) ;
}
B ( A )
构造函数中的this指向实例
function Fun ( value ) {
this . aaa = value
this . sing = function ( ) {
console. log ( this )
}
}
const myfun = new Fun ( 'bbb' )
myfun. sing ( )