How to change the context of a function in javascript

前端 未结 6 1738
醉梦人生
醉梦人生 2020-12-13 19:24

I\'m trying to understand why in javascript, you might want to change the context of a function. I\'m looking for a real world example or something which will help me unders

6条回答
  •  情书的邮戳
    2020-12-13 20:15

    It's very useful when doing callbacks from AJAX requests:

    function Person(_id, _name) {
        this.id = _id;
        this.name = _name;
    };
    
    Person.prototype.sayHi = function(greeting) {
        alert(greeting + " from " + this.name);
    };
    
    Person.prototype.loadFromAJAX = function(callback) {
        // in this example, it's jQuery, but could be anything
        var t = this;
        $.get("myurl.php", function(data) {
            callback.call(t, data.greeting);
        });
    };
    

    Actually, that's a pretty crappy example.

    There are tons of uses of it in jQuery. For example, the jQuery().get() function:

    get: function( num ) {
        return num === undefined ?
            // Return a 'clean' array
            Array.prototype.slice.call( this ) :
            // Return just the object
            this[ num ];
    }
    

    It's using the functions of the Array prototype but in the context of the jQuery object.

提交回复
热议问题