ce

【01】全局环境中的this

【01】全局环境中的this

 
 
 
 

【00】this绑定方式的优先级:

new绑定>显式绑定(如call)>隐式绑定(对象方法)>默认绑定(函数中变量)

 

 

 
 
【01】宿主为浏览器时,全局作用域中,this指向window对象。
console.log(this === window); //true
 

 

【02】浏览器中,在全局作用域中,使用var声明的变量实际是给this或window添加属性。

var foo = "bar";console.log(this.foo); //logs "bar"
console.log(window.foo); //logs "bar"
 

 

【03】任何情况下(全局作用域或函数作用域中),没有用var或let,cosnt声明变量,也是在给this或window添加属性。

foo = "bar";
function testThis() {
      foo = "foo";}console.log(this.foo); //logs "bar"
testThis();
console.log(this.foo); //logs "foo"
 
 

 

【04】Node脚本中global和this是区别对待的,而Node命令行中,两者可等效为同一个对象。

 

【05】在Node环境中执行的JS文件中,this是个空对象{},不等于global。

 

全局作用域中的var并不会将变量赋值给全局this,这与在浏览器中是不一样的。

未用var声明的变量会赋值给全局的global但不是this。

console.log(this);
console.log(this === global);
$ node test.js
{} false
【】例子:
var foo = "bar";
console.log(this.foo);
$ node test.js
undefined
【】例子:
foo = "bar";
console.log(this.foo);
console.log(global.foo);
$ node test.js
undefinedbar
 
 

 

【06】Node命令行(REPL)中,this是全局命名空间。this完全等于global,可以通过global来访问。

全局作用域中的var会将变量赋值给全局this,创建变量时没带var或let关键字会赋值给全局的this。

 

> this{ ArrayBuffer: [Function: ArrayBuffer],
  Int8Array: { [Function: Int8Array] BYTES_PER_ELEMENT: 1 },
  Uint8Array: { [Function: Uint8Array] BYTES_PER_ELEMENT: 1 },
  ...> global === this
true
【】例子:
> var foo = "bar";> this.foobar> global.foobar
 
 

**

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">

猜你喜欢

转载自www.cnblogs.com/moyuling/p/11105398.html
ce