This pointer is from an internal function.

I have JavaScript components that have the following architecture:

var MyComponent = function(params)
{
    setup(params);


    this.doSomething()
    {
        // doing something
    };

    function setup(params)
    {
        // Setup

        // Interaction logic
        var _this = this; // "this" points to DOMWindow, not to created object
        $(".some-element").click(function(){
            _this.doSomething(); // it craches here, because of above
        });
    }
};

When something controlled by the interaction logic happens, sometimes I have to forward the execution to the "public" methods of the component.

In this situation, I have a problem with the "this" pointer.

Sample code demonstrates this:

var Item = function()
{
    this.say = function()
    {
        alert("hello");
    };
    this.sayInternal = function()
    {
        _sayInternal();
    };
    function _sayInternal()
    {
        this.say();
    };
};

To check it out,

  • Create Object:

var o = new Item();

  • This works great:

o.say(); // alerts "hello"

  • Failure:

o.sayInternal();

I get an error message:

TypeError: the result of the expression 'this.say' [undefined] is not a function.

I think this behavior occurs because the _sayInternal () function is declared (and not assigned to an object, for example, this.say = function () "). Thus, it is distributed among all created objects and acts as a static function in C ++.

It's true?

+5
1

, sayInternal . , sayInternal, . .

this , . func(), this ( window ). obj.func(), this obj.

"" :

var method = obj.func;
method();

this . JavaScript , , .


call apply:

var MyComponent = function(params)
{
    setup.call(this, params); // <- using `call`

    this.doSomething()
    {
        // doing something
    };

    function setup(params)
    {
        // Setup  
        // Interaction logic
        var _this = this; // "this" to new  created object
        $(".some-element").click(function(){
            _this.doSomething();
        });
    }
};

:

var Item = function()
{
    this.say = function()
    {
        alert("hello");
    };
    this.sayInternal = function()
    {
        _sayInternal.call(this);
    };
    function _sayInternal()
    {
        this.say();
    };
};

, , this.sayInternal. , Item , , .

:

var Item = function() {
};

Item.prototype = (function() {
    function _sayInternal() {
        this.say();
    };

    return {
        say: function() {
            alert("hello");
        },
        sayInternal: function(){
            _sayInternal.call(this);
        }
    }
}());

, _sayInternal , () , say sayInternal . "" _sayInternal say sayInternal.

+3

All Articles