javascript - Is there a better method than setting a variable to this? - Stack Overflow

In my javascript objects i found myself writing this:this_object = this;It seems it's the only way

In my javascript objects i found myself writing 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?

In my javascript objects i found myself writing 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?

Share Improve this question edited Aug 26, 2010 at 0:49 Galen asked Aug 25, 2010 at 23:58 GalenGalen 30.2k9 gold badges74 silver badges90 bronze badges 1
  • See also: ‘this’ object can’t be accessed in private JavaScript functions without a hack? – Christian C. Salvadó Commented Aug 26, 2010 at 0:31
Add a ment  | 

5 Answers 5

Reset to default 5

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 mon 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 mon 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./yui/event/#customevent

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745671494a4639429.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信