2016-12-01 10 views
1

最初のレッスンはスコープです。Javascriptプロトタイプとスコープの操作

var scope = "global"; 
function Scope() { 
    var scope = "local"; 
    this.s = function() { return scope; } 
} 
var instance = new Scope(); 
console.log(instance.scope); ///this is 'undefined' 
console.log(instance.s()); /// this is 'local' 

これはクロージャの世界では理にかなっています。

次に、BaseScopeが導入されました。

function BaseScope() { 
    this.scope = "parent"; 
    this.h = function() {return "Hello";} 
} 
Scope.prototype = Object.create(BaseScope); 

はだから今、私はScopeBaseScopeのプロトタイプを追加したいです。以下は、私がを受け取りたいと考えていますが返されます。

var instance2 = new Scope(); 
console.log(instance2.s()); ///Should be returning 'local' because it is the fastest returned s() function on the object's prototype. 
console.log(instance2.scope); ///Should be returning BaseScope's scope, since it is technically the only defined 'scope' property up the chain. 
console.log(instance2.h()); ///Should return "Hello" 

最後の例では、私は完全に間違って何かをやっていると思わせるundefinedを返しています。上記の効果を得るためには、どのような措置を取る必要がありますか?

+0

あなたが 'にconsole.log(instance2.scope)で何を得るのですか;'? –

+0

@KubaWyrostek undefined –

+0

あなたの 'BaseScope'は決して実際には呼び出されません。 'scope'プロパティは決して' instance2'に割り当てられません。 'BaseScope'関数はプロトタイプとして扱うオブジェクトでもあります。 –

答えて

3

あなたは

scope.prototype = Object.create(BaseScope.prototype)としてスコープのプロトタイプにbasescopeにアクセスすることができます。

BaseScopeのスコープ変数にアクセスしたい場合は、スコープからBaseScopeを呼び出すだけで、BaseScope.call(this)を使用して呼び出すことができます。このスコープの範囲を変更することができます。

チェックこのスニペット

function Scope() { 
 
    BaseScope.call(this); 
 
    var scope = "local"; 
 
    this.s = function() { 
 
    return scope; 
 
    } 
 
} 
 

 
function BaseScope() { 
 

 
    this.scope = "parent"; 
 
    this.h = function() { 
 
    return "Hello"; 
 
    } 
 
} 
 
Scope.prototype = Object.create(BaseScope.prototype); 
 

 
var instance = new Scope(); 
 
console.log(instance.scope); ///this is 'undefined' 
 
console.log(instance.s()); 
 
console.log(instance.h());

+1

'Scope.prototype = Object.create(BaseScope.prototype);'という行は、プロトタイプチェーンをまったく扱わないため、不要です。 –

+1

'Scope()'の定義に 'BaseScope.call(this)'を入れないと、どうすればいいですか? –

+0

コンテキストを変更せずにBaseScopeの変数にアクセスすることはできません... call/applyを使って行うことはできません。このリンクをチェックしてくださいhttp://stackoverflow.com/questions/39417710/confusion-with-javascript-inheritance – Geeky

関連する問題