Javascript 回调中的范围
Scope in Javascript callback
我希望在第二个 console.log(this.items)
处看到数组 ["foo", "bar"]
。但是相反,我得到 undefined
.
如何获得 ["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));
只不过是适当地处理回调(没有基于聚合物)。
我希望在第二个 console.log(this.items)
处看到数组 ["foo", "bar"]
。但是相反,我得到 undefined
.
如何获得 ["foo", "bar"]
而不是 undefined
?
<!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));
只不过是适当地处理回调(没有基于聚合物)。