【问题标题】:Using a "shortcut" function gives me a "Illegal invocation” error [duplicate]使用“快捷方式”功能会给我一个“非法调用”错误 [重复]
【发布时间】:2017-04-28 19:29:28
【问题描述】:

我在 Javascript ES6 中有这段代码:

// Create a new object
var foo = new A();

// Create shortcuts to use localStorage faster
foo.set = window.localStorage.setItem;
foo.get = window.localStorage.getItem;

// Try to use localStorage 
foo.set('count', 1);

但我在最后一行得到“非法调用”,我不明白为什么。

知道如何解决这个问题吗?

【问题讨论】:

  • 您正在更改函数的上下文 (this)。

标签: javascript ecmascript-6 local-storage


【解决方案1】:

您正在更改 this 的方法上下文。使用Function#bindthis 设置为localStorage

var foo = {};
undefined
foo.set = window.localStorage.setItem.bind(localStorage);
foo.get = window.localStorage.getItem.bind(localStorage);

// Try to use localStorage
foo.set('count', 1);
console.log(foo.get('count'));

或者,您可以创建一个调用 localStorage 函数的包装函数。

foo.set = (k,v) => window.localStorage.setItem(k,v)
foo.get = (k) => window.localStorage.getItem(k)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多