我有一些基本的角度代码抓取登录和注销用户的导航菜单,并将菜单存储在$localStorage
中,然后在用户登录/退出时将其切换到$rootScope
以下是针对此问题的该代码的简化版本。
似乎其中一行代码实际上导致左侧被分配到右侧。
$localStorage.navigation = {};
$rootScope.nav = {};
// save the nav menus in local storage
$localStorage.navigation.loggedIn = "nav menu json";
// use local storage to set the rootscope
$rootScope.nav = $localStorage.navigation;
/* should be..
$rootScope.nav = {loggedIn:'nav menu json'};
$localStorage.navigation = {loggedIn:'nav menu json'};
*/
// set the nav menu - Right-hand-assignment???
$rootScope.nav.current = $localStorage.navigation.loggedIn;
/* should be..
$rootScope.nav = { loggedIn:'nav menu json', current: 'nav menu json' };
$localStorage.navigation = { loggedIn:'nav menu json' };
*/
console.log($rootScope.nav.current); // 'nav menu json' as expected
console.log($localStorage.navigation.current); // 'nav menu json', WHAT??!!
/* actually..
$rootScope.nav = { loggedIn:'nav menu json', current: 'nav menu json' };
$localStorage.navigation = { loggedIn:'nav menu json', current: 'nav menu json' };
*/
这到底是怎么回事?
答案 0 :(得分:3)
由于$localStorage.navigation
是一个不是原语的对象(Boolean
,Number
,String
),因此该行会分配引用,而不是复制 $localStorage.navigation
至$rootScope.nav
:
$rootScope.nav = $localStorage.navigation;
此时,$localStorage.navigation
和$rootScope.nav
是对完全相同对象的两个引用。这一行:
$rootScope.nav.current = $localStorage.navigation.loggedIn;
将原始值$localStorage.navigation.loggedIn
分配给$rootScope.nav.current
,但由于$localStorage.navigation
和$rootScope.nav
是完全相同的对象,$localStorage.navigation.current
引用的值与$rootScope.nav.current
要明确的是,右侧分配不可能。