1:在構造函數內部使用嚴格模式,這樣this的指向為undefined,為uneducated添加屬性和方法會直接報錯!
function Foo() { 'use strict' this.name = 'zhangsan'; this.age = 18; } //TypeError: Cannot set property 'name' of undefined var a = Foo();
2:使用instanceof判斷tthis的指向
function Foo() { if (!(this instanceof Foo)) throw new Error('cuowu!'); this.name = 'zhangsan'; this.age = 18; } //Error: cuowu! var a = Foo();
這里如果默認調用this會指向全局對象,而如果使用new調用,this的指向為Foo的實例對象.。
3:使用new target方法判斷
function Foo() { if (new.target !== Foo) throw new Error('cuowu!'); this.name = 'zhangsan'; this.age = 18; } //Error: cuowu! var a = Foo();
如果不是new調用,target默認指向的是undefined。