我们能否在所有javascript方法中定义“this”的值

Can we define the value of "this" in all javascript methods?

本文关键字:定义 this 的值 方法 javascript 我们      更新时间:2023-09-26

所以我有一个骨干视图,我有这个方法

inscription: function() {
    var self = this;
    navigator.geolocation.getCurrentPosition(function(position) {
    //I need to use self here because the context of this function
    //is not my Backbone View

如何在 getCurrentPosition 回调中使用它

使用 _.bind - _.bind(fn, context) 在您的情况下:

var self = this;
//...
var somefn = _.bind(function(position) {
   var self = this;
   //this/self refer to outer this
}, self)
navigator.geolocation.getCurrentPosition(somefn)