this

2019-03-30  本文已影响0人  Duobe

In the browser

> this === window // => true

> "use strict";
  this === window // => true

In node

a. 命令行

> node // => 进入node
> this === global   // => true

b. node执行以下文件node index.js

// index.js
console.log(this === global) // => false
console.log(this === module.exports) // => true

c. in function call

function func () { 
  console.log(this === global) // => true
}

func()
"use strict"; 
function func () { 
  console.log(this === undefined) // => true
}

func()
function func () { 
  "use strict"; 
  console.log(this === undefined) // => true
}

func()

e. in constructor call

function Person (firstName, lastName) { 
  this.firstName = firstName;
  this.lastName = lastName;
}

const person = Person("Jane", "Doe")

console.log(person) // => undefined
function Person (firstName, lastName) { 
  this.firstName = firstName;
  this.lastName = lastName;
}

const person = Person("Jane", "Doe")

console.log(person) // => undefined

console.log(global.firstName) // => Jane
console.log(global.lastName) // => Doe
// output: 
// this.firstName = firstName;
//                ^
//
// TypeError: Cannot set property 'firstName' of undefined ...
"use strict";
function Person (firstName, lastName) { 
  this.firstName = firstName;
  this.lastName = lastName;
}

const person = Person("Jane", "Doe")

console.log(person) 

console.log(global.firstName)
console.log(global.lastName)
"use strict";
function Person (firstName, lastName) { 
  this.firstName = firstName;
  this.lastName = lastName;
}

const person = new Person("Jane", "Doe")

console.log(person) // => Person { firstName: 'Jane', lastName: 'Doe' }

console.log(global.firstName) // => undefined
console.log(global.lastName) // => undefined

more

上一篇下一篇

猜你喜欢

热点阅读