右侧任务 - 这怎么可能?

时间:2017-06-16 03:13:22

标签: javascript javascript-objects

我有一些基本的角度代码抓取登录和注销用户的导航菜单,并将菜单存储在$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' };
*/

这到底是怎么回事?

1 个答案:

答案 0 :(得分:3)

由于$localStorage.navigation是一个不是原语的对象(BooleanNumberString),因此该行会分配引用,而不是复制 $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

要明确的是,右侧分配不可能