我认为这应该很简单,但对于我的一生,我无法使其正常运行。
我有一个角度字符串(占位符),我想从$ document.ready()上触发的jQuery函数中引用它。基本上这就是我所拥有的:
placeholder: string;
ngOnInit() {
this.translateService.get(['']).subscribe(translations => {
this.placeholder = this.translateService.instant('placeholder');
console.log('PLACEHOLDER', this.placeholder); <<<<<<<<< has expected value
});
$(document).ready(function () {
console.log('READY', this.placeholder); <<<<<<<<< undefined
$('#dropDown').select2({
placeholder: this.placeholder,
data: [
...
]
});
});
}
我如何从jQuery函数中引用this.placeholder?
this.placeholder = 'Foo';
$(document).ready(function () {
console.log('READY', this.placeholder); // this is another this, local to the function
}
有两种解决方案:
使用旧JS在纯JS中,您可以移开外部
this
以便在内部使用它:
this.placeholder = 'Foo'; var that = this; $(document).ready(function () { console.log('READY', that.placeholder); // that refers to the outer this }
使用现代JS(ECMA脚本> 5)
如果您可以使用具有ECMA脚本> 5的现代浏览器,则可以使用箭头功能()=>{}
代替function(){}
,它会自动保留外部的this:
this.placeholder = 'Foo'; $(document).ready(() => { console.log('READY', this.placeholder); // () => {} does not override this }
export class TestComponent implements OnInit {
placeholders:Array<string> = [];
constructor() { }
ngOnInit() {
// removed function keyword and added () => {} syntax
$('#btn').on('click', (e, arr) => {
console.log(this.placeholders);
});
}