Javascript This &New

159 阅读1分钟

this 规则

Javascript标准定义了[[thisMode]]私有属性,有三个取值

  • lexical: 从上下文中寻找this,如箭头函数。逐层检查当前词法环境中的[[ThisBindingStatus]],直到找到有This的环境记录时获取this的值
	console.log(this);
    return () =>{
    	   console.log (this);
           return() =>console.log(this);
           }
      }
//run in chrome console      
o.foo()
//output
VM684:1 {a: 1, foo: ƒ}
() =>{console.log (this);
                                    return() =>console.log(this);}
//run in chrome console
o.foo()()

//chrome output

VM684:1 {a: 1, foo: ƒ}
VM684:2 {a: 1, foo: ƒ}

() =>console.log(this)

//run in chrome console
o.foo()()()

//chrome output
VM684:1 {a: 1, foo: ƒ}
VM684:2 {a: 1, foo: ƒ}
VM684:3 {a: 1, foo: ƒ}
  • global: 当this为undefined时,取全局对象,对应普通函数
  • strict: 严格模式时,this 严格按照调用时传入的值,可能为null或undefined

new

  • 以构造器的prototype属性为原型,创建新对象
  • 将this和调用参数传给构造器,执行
  • 如果构造器返回的是对象,则返回该对象,否则返回第一步创建的对象
  • 仅仅普通函数和类能和new搭配使用