2015-02-11 46 views
0

我想我明白瞭如何在javascript中工作call,但顯然不是。爲什麼我的上下文不能共享?

function bear(){ 
    var a = 1 
    pig.call(this) 
} 

function pig(){ 
    alert(a) //throws an error, 'a is not defined' 
} 

bear() 

http://codepen.io/anon/pen/jEYGOv

爲什麼不這項工作?我怎樣才能使它工作(沒有通過a作爲變量)

+1

由於* this *是一個執行上下文的參數,它不代表該cont分機(無論人們多麼頻繁地將其稱爲「上下文」)。你不能引用執行上下文,語言規範禁止它。 – RobG 2015-02-11 03:44:27

+0

@RobG謝謝 - 這澄清了很多。它也很糟糕。 – 2015-02-11 03:48:11

回答

1

你不能做到這一點。

function bear(){ 
    pig.call(this); 
} 

function pig(){ 
    this.a = 5; //same as window.a = 5 unless used as a constructor; 
} 
bear(); //window.a == 5; 
a = new bear(); //this keyword is now referring to variable object a so a.a = 5; 

而且第一個爲.call(this)後的任何參數將是功能的,你在

+1

請注意,在嚴格模式下,* this *將會是未定義的, this.a *會拋出一個錯誤。 – RobG 2015-02-11 03:48:39

0

你需要看一看在scope of variables

<script type="text/javascript"> 
var a; 

function bear(){ 
    a = 1 
    pig.call(this) 
} 

function pig(){ 
    alert(a); 
} 

bear(); 
</script> 
+1

是的,但這種方式不需要執行'call()'部分,因爲它會全局設置'a'變量並且無論如何都會提醒它 – rsz 2015-02-11 03:36:14

1

調用call()參數爲什麼不這項工作?我怎樣才能使它發揮作用(而沒有經過作爲 變量)

你在這裏做什麼是Function.prototype.call共享的上下文。共享上下文不共享範圍變量。範圍變量不能從範圍之外訪問,並且pig()在與bear()不同的範圍內運行。

你可以做的是

一)發送的參數的公共變量:。

// recommended 

function bear(){ 
    var a = 1; 
    pig(a); 
} 

function pig(a){ 
    alert(a); 
} 

bear(); 

B)定義對象是共同環境:

// not recommended 
// hard to follow where the context is coming from 

function bear(){ 
    this.a = 1; 
    pig.call(this); 
} 

function pig(){ 
    alert(this.a); 
} 

var o = {}; 
bear.call(o); 

// recommended 

var o = { 
    a: undefined, 
    bear: function(){ 
     this.a = 1; 
     this.pig(); 
    }, 
    pig: function pig(){ 
     alert(this.a); 
    } 
}; 

o.bear(); 

角)定義一個類

// not recommended 
// you are defining the methods (bear and pig) by each instantiation 

var My = function(){ 
    this.bear = function(){ 
     this.a = 1; 
     this.pig(); 
    }; 
    this.pig = function pig(){ 
     alert(this.a); 
    }; 
}; 

var o = new My(); 
o.bear(); 

// recommended 

var My = function(){}; 
My.prototype = { 
    constructor: My, 
    a: undefined, 
    bear: function(){ 
     this.a = 1; 
     this.pig(); 
    }, 
    pig: function pig(){ 
     alert(this.a); 
    } 
}; 

var o = new My(); 
o.bear(); 

d。)在上部範圍

// not recommended 
// (unless we are talking about a commonjs module which has its own scope) 
// don't pollute the global scope with local variables 

var a; 

function bear(){ 
    a = 1; 
    pig(a); 
} 

function pig(a){ 
    alert(a); 
} 

bear(); 

或閉合定義公共變量

// recommended 

(function(){ 
    var a; 

    function bear(){ 
     a = 1; 
     pig(a); 
    } 

    function pig(a){ 
     alert(a); 
    } 

    bear(); 
})(); 
相關問題