質問

The following code is used as in inheritance method in JavaScript but I am having trouble following the code, specifically the context of "this" so I've added questions as code comments. Thanks in advance for the enlightenment.

var Class = function(){
    var klass = function(){
        //Is "this" referring to the Class class or Klass class?
        //Why is "this" being applied to "this.init"? Isn't this default behavior? 
        //Are they both the same "this"?
        this.init.apply(this, arguments);
    };
    klass.prototype.init = function(){};
    return klass;
};

var Person = new Class;

Person.prototype.init = function(){
// Called on Person instantiation
};

// Usage:
var person = new Person;

Apologies if I'm misinterpreting this whole thing.

役に立ちましたか?

解決

this always refers to the caller of a function. If you call a function like person.init() then this refers to the Person instance. If you call a function without specifying the this like alert() then it will refer to the window.

Is "this" referring to the Class class or Klass class?

Neither, exactly. In the end, it refers to the new Person instance that you're creating.

Why is "this" being applied to "this.init"? Isn't this default behavior?

If you don't prefix with this then it's going to assume you're talking about some other variable/function, typically a global unless you have a closure.

Are they both the same "this"?

If by both you mean Class and klass then no. As the first question states: this is determined by the caller or new.

One thing that may be confusing is the use of apply. All that apply does it allows you to set the caller of a function before calling it and pass any arguments as an array. The reason they do this is to allow the user to pass their own arguments. For example, say we have the following two init functions:

Person.prototype.init = function(name) {
    this.name = name;
};

Person2.prototype.init = function(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
};

klass needs to have some way of passing in those arguments to the init functions. It does this using apply. So the following are functionally equivalent:

var klass = function(a, b) {
    this.init(a, b);
};

// This one can take ANY number of arguments, not just two
var klass = function() {
    this.init.apply(this, arguments);
};

This works because arguments is essentially an array of the passed arguments.

他のヒント

Lots of good questions and answers on SO concerning Javascript scope, but the key concept to understand is.. the value of the variable this is established by the caller. The answer to your question - "this" could point to almost anything.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top