gpt4 book ai didi

javascript - Javascript 回调的范围

转载 作者:行者123 更新时间:2023-12-02 15:05:31 24 4
gpt4 key购买 nike

我希望在第二个 console.log(this.items) 处看到数组 ["foo", "bar"]。但相反,我得到了未定义

Here is the jsBin .

如何获取 ["foo", "bar"] 而不是 undefined

http://jsbin.com/hodegimohu/edit?html,控制台,输出
<!doctype html>
<head>
<meta charset="utf-8">
<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

</head>
<body>

<dom-module id="x-element">
<script>
(function(){
Polymer({
is: 'x-element',
properties: {
items: {
type: Array,
value: ['foo','bar']
},
},
ready: function(){
console.log(this.items) // ["foo", "bar"]
google.charts.load('current', {
'packages': ['geochart']
});
google.charts.setOnLoadCallback(this._drawRegionsMap);
},
_drawRegionsMap: function() {
console.log(this.items); // undefined
},
});
})();
</script>
</dom-module>
<x-element></x-element>
</body>

最佳答案

只需使用.bind

google.charts.setOnLoadCallback(this._drawRegionsMap.bind(this));

只不过是适本地处理回调(不基于 polymer )。

关于javascript - Javascript 回调的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35137473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com