AngularJs 解构 $location

AngularJs destructuring $location

而不是使用:

const ref = $location.protocol() + '://' + $location.host();

我试着这样做:

const { protocol, host } = $location;
const ref = protocol() + '://' + host();

但是好像不行。 ( protocol() 不返回任何东西,对于 host() 也是如此) 但是,如果我尝试这样的事情:

const loc = {
    protocol: function(){
        return 'http';
    },
    host: function(){
        return 'example.com';
    },
};

const { protocol, host } = loc;

document.write(protocol() + '://' + host());

有效。知道为什么吗?

Ps。一些示例 here,只需取消注释第二行,它就不再起作用了。

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

当您使用 de-structure 方法时,您丢失了对此的引用,$location.protocolprotocol 引用了不同的 this

let a = {
  myName : 'my name',
  nameLogger(){
    return this.myName
  }
}

let {nameLogger} = a

console.log( 'Hello ' + nameLogger())

nameLogger = nameLogger.bind(a)

console.log( 'Hello ' + nameLogger())