简体   繁体   中英

Using Google Drive API with Javascript prototypes

So instead of doing the standard copy & paste from the examples in Google's docs of Javascript with global variables, I want to encapsulate everything using prototypes.

My function starts with this:

define(function (require){
    'use strict';
    ...

but the interesting point at which I am blocked now is:

GoogleDrive.prototype.loadAPI = function() {
    window.gapi.load('picker', {'callback': this.onPickerApiLoad});
};

GoogleDrive.prototype.onPickerApiLoad = function() {
    this.pickerApiLoaded = true;
    this.createPicker();
};

That doesn't work because this inside the callback is not my GoogleDrive function any more, so I get:

Uncaught TypeError: Cannot set property 'pickerApiLoaded' of undefined

How would I connect that .onPickerApiLoad to the right scope?

UPDATE:

Prompted by @Jon's answer, I looked into Underscore's bind method source code and it uses call , so I tried to do the same, with a function that returns a version of my prototype function bound to the context I want:

GoogleDrive.prototype.loadAPI = function() {
        var that = this;
        googleAPI.load('picker', {'callback': function() { return that.onPickerApiLoad.call(that) }});
    };

This seems to work (have to confirm), but not that elegant.

I bet you could get this to work using the bind function of Underscore or Lo-Dash (a drop-in Underscore replacement):

GoogleDrive.prototype.loadAPI = function() {
    window.gapi.load('picker', {'callback': _.bind(this.onPickerApiLoad, this)});
};

I finally resorted to call and an anonymous function, using which I can pass my own context:

var that = this;
googleAPI.load('picker', { 'callback': function() {
    return that.onPickerApiLoad.call(that)
} } );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM