开发者

Is there a better method than setting a variable to this?

开发者 https://www.devze.com 2023-01-14 09:28 出处:网络
In my javascript objects i found myself wri开发者_运维知识库ting this: this_object = this; It seems it\'s the only way to pass member variables to external functions...

In my javascript objects i found myself wri开发者_运维知识库ting this:

this_object = this;

It seems it's the only way to pass member variables to external functions...

google.maps.event.addListener(this.marker, 'click', function() {
    this.info_window.setContent('Chicago marker');
    this.info_window.open(this.map,this.marker);
});

That doesn't work, I have to copy the object into a member variable and pass the new object (and replace all this with this_object)

This feels ugly. Is there a "better" or "cleaner" way, or is this my only option?


Sure there is a better method. It involves creating a function which has the this context already bound to a particular object.

To have the this context refer to the current object, call the bind() method on the function and pass the required context as a parameter.

google.maps.event.addListener(this.marker, 'click', function() {
    this.info_window.setContent('Chicago marker');
    this.info_window.open(this.map,this.marker);
}.bind(this)); // <-- notice we're calling bind() on the function itself

This is now part of the ECMAScript standard, and if a browser does not implement it natively, it's easy to do it yourselves.

if (!Function.prototype.bind) {
    Function.prototype.bind = function () {
        var fn = this,
            args = Array.prototype.slice.call(arguments),
            object = args.shift();

        return function () {
            return fn.apply(
                object, args.concat(Array.prototype.slice.call(arguments))
            );
        };
    };
}

See all questions and answers on SO related to this.


It's actually a pretty common pattern when dealing with JavaScript to store a reference of this in a local variable i.e. var myThing=this;. Remember functions have access to local variables defined in their scope. Any variables defined in the containing functions are accessible.


You'll find this piece of code quite frequent in many libraries and projects :

function someFunction() {
   var that = this;

   //....
}

For example, consider this function :

function container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;

    return function () {
        if (dec()) {
            return that.member + " " + secret;
        } else {
            return null;
        }
    };
}

var c = container("foo");
alert( c() ); // "foo 2";
alert( c() ); // "foo 1";
alert( c() ); // "foo 0";
alert( c() ); // null;

Read more here.


I have seen the pattern before (with the variable in question being called), so I assume it is indeed a common javascript pattern that does not just have a cleaner solution.


I'm not certain this will help whatever scenario you are dealing with, but I've found YUI's custom event utility to work nicely with scoping issues with this and closures. It's an event-driven model, and a slightly different way of thinking, but it might be worth exploring at least.

http://developer.yahoo.com/yui/event/#customevent

0

精彩评论

暂无评论...
验证码 换一张
取 消