Why *this* is not *this*?

2019-04-07 13:45发布

I just wrote this piece of code to represent this error that is killing me (Grrr!)

I wonder why when I get error: method undefined I have checked in Safari and this variable inside parserDidStart() method is not of type EpisodeController it is of type EpisodeFeedParser why is this?

<html>
<head>
<script type="text/javascript">
var EpisodeFeedParser = function(url){
    this.url = url;
    this.didStartCallback = null;
};
EpisodeFeedParser.prototype.parse = function(doc){
    this.didStartCallback(this);
};

var EpisodeController = function(){
    this.episodes = new Array();
    this.parser = null; //lazy
};
EpisodeController.prototype.parserDidStart = function(parser){
    console.log("here *this* is not of type EpisodeController but it is EpisodeFeedParser Why?");
    this.testEpi(); //**********ERROR HERE!***********
};
EpisodeController.prototype.fetchEpisodes = function(urlString){
    if(urlString !== undefined){
        if(parser === undefined){
            var parser = new EpisodeFeedParser(urlString);
            parser.didStartCallback = this.parserDidStart;
            this.parser = parser;
        }
        this.parser.parse();
    }
};
EpisodeController.prototype.testEpi = function(){
console.log("it worked!");
};

function testEpisode(){
    var controller = new EpisodeController();
    controller.fetchEpisodes("myurl");
}
</script>
</head>
<body>
<button type="button" onclick="testEpisode()">press me</button>
</body>
</html> 

5条回答
Bombasti
2楼-- · 2019-04-07 14:18

Try:

var that = this;
parser.didStartCallback = function(parser) {
  that.parserDidStart(parser);
};

This creates a closure that passes in the correct scope to parserDidStart. Currently, when you call this.parser.parse(), it passes the EpisodeFeedParser as context, as that's where it's called from. It's one of the quirks of scope in JavaScript, and can be pretty frustrating.

查看更多
一纸荒年 Trace。
3楼-- · 2019-04-07 14:27

this is a frequently misunderstood aspect of Javascript. (and by "this", I mean this)

You can think of this as another parameter that gets invisibly passed in to your functions. So when you write a function like,

function add (a,b) {
   return a+b;
}

you're really writing

function add(this, a, b) {
    return a+b;
}

That much is probably obvious, what isn't obvious is exactly what gets passed in, and named as "this". The rules for that are as follows. There are four ways to invoke a function, and they each bind a different thing to this.

classic function call

add(a,b);

in the classic function call, this is bound to the global object. That rule is now universally seen as a mistake, and will probably be set to null in future versions.

constructor invocation

new add(a,b);

in the constructor invocation, this is set to a fresh new object whose internal (and inaccessible) prototype pointer is set to add.prototype

method invocation

someobject.add(a,b);

in the method invocation, this gets set to someobject. it doesn't matter where you originally defined add, whether it was inside a constructor, part of a particular object's prototype, or whatever. If you invoke a function in this way, this is set to whatever object you called it on. This is the rule you are running afoul of.

call/apply invocation

 add.call(someobject,a,b);

in the call/apply invocation, this is set to whatever you pass in to the now visible first parameter of the call method.

what happens in your code is this:

 this.parser.didStartCallback = this.parserDidStart;

while you wrote parserDidStart with the expectation that its this would be an EpisodeController when you method invoke it... what actually happens is you're now changing its this from the EpisodeController to this.parser. That's not happening in that particular line of code. The switch doesn't physically happen until here:

this.didStartCallback(this);

where this in this instance is the EpisodeParser, and by the time this code is run, you've asigned parserDidStart to be named didStartCallback. When you call didStartCallback here, with this code, you're essentially saying...

didStartCallback.call(this,this);

by saying this.didStartCallback() ,you're setting its this to.. well.. the this when you call it.

You should be aware of a function called bind, which is explained here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

Bind creates a new function from an existing function, whose this is fixed (bound) to whatever object you explicitly pass in.

查看更多
手持菜刀,她持情操
4楼-- · 2019-04-07 14:32

this passed to didStartCallback in

EpisodeFeedParser.prototype.parse = function(doc){
    this.didStartCallback(this);

is of type EpisodeFeedParser

and in EpisodeController.prototype.fetchEpisodes you affect EpisodeController.parserDidStart to parser.didStartCallback:

parser.didStartCallback = this.parserDidStart;

so this.didStartCallback(this); is in fact EpisodeController.parserDidStart(this)

and we saw at the beginning that this last this was of type EpisodeFeedParser.

Q.E.D

查看更多
来,给爷笑一个
5楼-- · 2019-04-07 14:32

The problem is that "didStartCallBack" is being called on (and in the context of) "this", at a point in execution when "this" refers to the EpisodeFeedParser. I have fixed it using .call(), though I'm not sure why you'd need to write code this roundabout, I'm sure there must be a reason.

Important change:

parse: function(episodeController){
  this.didStartCallback.call(episodeController, this);
}//parse

Full Code:

<html>
<head>
<script type="text/javascript">
    //An interesting context problem...
    //Why is it of type EpisodeFeedParser?

    // ---- EpisodeFeedParser
    var EpisodeFeedParser = function(url){
        this.url = url;
    };  
    EpisodeFeedParser.prototype = {
        url:null,
        didStartCallback:null,
        parse: function(episodeController){
            this.didStartCallback.call(episodeController, this);
        }//parse
    }//prototype


    // ---- EpisodeController
    var EpisodeController = function(){
        this.episodes = new Array();
        this.parser = null; //lazy
    };

    EpisodeController.prototype = { 
        parserDidStart: function(parser){
            console.log("here *this* is not of type EpisodeController but it is EpisodeFeedParser Why?");
            debugger;
            this.testEpi(); //**********ERROR HERE!***********
        },

        fetchEpisodes: function(urlString){
            if(urlString !== undefined){
                if(this.parser === null){
                    this.parser = new EpisodeFeedParser(urlString);
                    this.parser.didStartCallback = this.parserDidStart;
                }//if
                this.parser.parse(this);
            }//if
        },//fetchEpisodes

        testEpi: function(){
            console.log("it worked!");
        }
    }//EpisodeController.prototype


    // ---- Global Stuff
    function testEpisode(){
        var controller = new EpisodeController();
        controller.fetchEpisodes("myurl");
    }
</script>
</head>

<body>
<button type="button" onclick="testEpisode()">press me</button>
</body>
</html> 
查看更多
劫难
6楼-- · 2019-04-07 14:32
EpisodeFeedParser.prototype.parse = function(doc){
    this.didStartCallback(this);
};

I don't understand why you'd expect this to be anything other than an EpisodeFeedParser.

查看更多
登录 后发表回答