2017-10-27 7 views
0

ローカル変数は関係なく、グローバルな1

var construct = function() { 
 
    var self = this; 
 

 
    var view = { 
 
    name: "self" 
 
    }; 
 

 
    self.vm = { 
 
    attached: attached, 
 
    view: view 
 
    } 
 

 
    function attached() { 
 
    alert('view.name: ' + view.name); 
 
    view = { 
 
     name: "attached" 
 
    }; 
 
    alert('view.name(after attached): ' + view.name); 
 
    alert('self.vm.view.name: ' + self.vm.view.name); 
 
    alert('this.view.name: ' + this.view.name); 
 
    } 
 

 
    self.vm.attached(); 
 

 
    return self.vm; 
 
}()

は、あなたが見ることができるように、我々は(オブジェクトをselv.vmに関連する)グローバルな文脈における変数「ビュー」があります。 ビューは、参照によってself.vmオブジェクトに渡されます。

これを知っていると、 'attached'メソッドはグローバル変数を変更し、その結果、self.vm.viewは新しいオブジェクトを指すことになります。

新しいローカル変数が作成され、同じ名前のグローバルが存在するかどうかは関係ありません。

予期しない動作ではありませんか?なぜそうなの?骨子例にこれをダウン沸騰さ

+0

アラートに表示されている値を書き込むこともできます。 – lakshay

+0

* "...その結果、self.vm.viewは新しいオブジェクトを指します。" *これは間違っています。 – Yoshi

答えて

2

への参照を保持している、あなたは基本的に新しく作成されたオブジェクトに、あなたのview変数を再割り当てされています。あなたは既存のオブジェクトを変更していない、オブジェクトはまだそこにあります。 self.vm.viewviewの初期値への参照を保持するので、self.vm.view.nameを実行するとその値が表示されます。

変更をしたい場合viewがポインタであるので、あなたが

view.name = "attached"; 
2

var a = {name: 'one'}; 
 
var b = {view: a}; 
 

 
// See what b.view holds 
 
console.log(b.view); 
 

 
// Change a and look again 
 
a = {name: 'two'}; 
 
console.log(b.view);

我々は、オブジェクトにどの参照a点を変更しました。しかしb.viewはまだfunction attached()インサイド(それが再割り当てされた前aが指さ)元のオブジェクト

1

を行うためにきた元のオブジェクトの値がそれです。

var construct = function() { 
    var self = this; 

    // this create a new object, with the property name being "self" 
    // and "view" as a pointer to that object 
    var view = { 
    name: "self" 
    }; 

    self.vm = { 
    attached: attached, 
    // here the property "view" of the "vm" object points to the variable "view", which itself points to the original object (the one with name="self") 
    view: view 
    } 

    function attached() { 
    // the pseudo-global "view" object is called, it reaches out to the object it points to and gives us the name: "self" 
    alert('view.name: ' + view.name); 
    // now we are changing "view" to point to a NEW object, with the property name="attached" 
    view = { 
     name: "attached" 
    }; 
    // view points to the new object, it's name is "attached" 
    alert('view.name(after attached): ' + view.name); 
    // the "view" property of self.vm still points to the original object, the one with the name "self" 
    alert('self.vm.view.name: ' + self.vm.view.name); 
    alert('this.view.name: ' + this.view.name); 
    } 

    self.vm.attached(); 

    return self.vm; 
}() 

Javascript by reference vs. by valueもご覧ください。たぶんそれは私よりも良いことを説明することができます。

これは難しい問題です。

関連する問題