指定 “use strict“ 后 js 里的 this 

指定严格模式  "use strict"; 后

 

如果没指定函数里的this,this不再指向 globle

function fn(name) {
  this.name = name
}

let f1 = new fn('wjs'); // 执行后 f1.name 的值为 wjs
let f2 = fn('wjs');     // 忘了加new 报错 this未定义

// 这里的 this 指向 module.exports, 传给 fn 后
// fn 里的this 也指向了 module.exports
// fn 给module.exports添加了 name 属性, 值为 fn.call
fn.call(this, "fn.call"); 
console.log(module.exports.name); // fn.call

 

forEach 调用回调时没有指定this, 因此function回调 需要显式指定 this

let wjs = {
  name:"wjs",
  
  talk(names){
    // =>回调 没有this, 于是this就使用了wjs的
    names.forEach(e => console.log(this.name, e));

    // function回调中的this 要显式指定,否则为 undefine
    let self = this
    names.forEach(function (e) { console.log(self.name, e); });
  },
}
wjs.talk(["wjl","wsh"]);

 

events 调用回调时指定了 this, 指定为EventEmitter 

const EE = require('events');

const ee = new EE();

// =>回调 没有this, 所以忽略了 ee的指定, =>中的 this 就是外层的 this, 此处即module.exports
ee.on('close', (...args) => {console.log(this, ...args);} )

// function回调,接受了 ee指定的EventEmitter
ee.on('close', function(...args) {console.log(this, ...args);} )

ee.emit('close', "this", "is", "message");

 

附录, 完整示例代码 

"use strict";

function fn(name) {
  this.name = name
}

let f1 = new fn('wjs'); // 执行后 f1.name 的值为 wjs
//let f2 = fn('wjs');     // 忘了加new 报错 this未定义

// 这里的 this 指向 module.exports 传给 fn 后
// fn 里的this 也指向了 module.exports
// 给module.exports添加了 name 属性, 值为 fn.call
fn.call(this, "fn.call"); 
console.log(module.exports.name); // fn.call

let wjs = {
  name:"wjs",
  
  talk(names){
    // => 和 function的区别, => 没有this, 于是this就使用了wjs的
    // foreach callback 的 this undefine  语法错误
    names.forEach(e => console.log(this.name, e));
    
    let self = this
    names.forEach(function (e) { console.log(self.name, e); });
  },
}
wjs.talk(["wjl","wsh"]);


const EE = require('events');

const ee = new EE();

ee.on('close', (...args) => {console.log(this, ...args);} )
ee.on('close', function(...args) {console.log(this, ...args);} )

ee.emit('close', "this", "is", "message");

 

输出

fn.call
wjs wjl
wjs wsh
wjs wjl
wjs wsh
{ name: 'fn.call' } this is message
EventEmitter {
  _events: [Object: null prototype] { close: [ [Function], [Function] ] },
  _eventsCount: 1,
  _maxListeners: undefined,
  [Symbol(kCapture)]: false
} this is message

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值