function makeNoSense(x) { this.x = x; } makeNoSense(5); console.log(x);// x 已經成爲一個值爲 5 的全局變量
function test(){ this.x = 1; alert(this.x); } test(); // 1
狀況二:做爲對象方法的調用java
函數還能夠做爲某個對象的方法調用,這時this指代對象內部屬性被調用。編程
var myObject = { value :0, increment:function (inc){ this.value += typeof inc ==='number' ? inc:1; } }; myObject.increment(); console.log(myObject.value); //1 myObject.increment(2); console.log(myObject.value); //3
狀況三 :做爲構造函數調用數組
function Point(x, y){ this.x = x; this.y = y; } var p1 = new Point(3,2); console.log(p1.x+","+p1.y);//3,2
爲了代表這時this不是全局對象,我對代碼作一些改變:app
var x = 4; function Point(x, y){ this.x = x; this.y = y; } var p1 = new Point(3,2); console.log(p1.x+","+p1.y);//3,2
狀況四: apply或call調用編程語言
function Point(x, y){ this.x = x; this.y = y; this.moveTo = function(x, y){ this.x = x; this.y = y; console.log(this.x+","+this.y); } } var p1 = new Point(0, 0); var p2 = {x: 0, y: 0}; p1.moveTo(1, 1); //1,1 p1.moveTo.apply(p2, [10, 10]);//10,10
在上面的例子中,咱們使用構造函數生成了一個對象 p1,該對象同時具備 moveTo 方法;使用對象字面量建立了另外一個對象 p2,咱們看到使用 apply 能夠將 p1 的方法應用到 p2 上,這時候 this 也被綁定到對象 p2 上。另外一個方法 call 也具有一樣功能,不一樣的是最後的參數不是做爲一個數組統一傳入,而是分開傳入的。本文經過對JavaScript中常常容易混淆的this在四中應用場景中的使用方法進行了講解,但願對您有所幫助,喜歡的話,請推薦一下哦。函數