0
Class.method = function () { this.xx }
Class.prototype.method = function () { this.xx }
var clazz = new Class();
clazz.method();

When I call the 4th line this in the function will refer to clazz But when Class.method() is executed, what will this refer to?

1
  • It will refer to new object Class = new Object() or Class = function(){} Commented Dec 2, 2011 at 13:46

4 Answers 4

1

this within the Class.prototype.method function will still refer to the Class instance. This isn't a static method, a static (i.e. one per class) method would be something like:

Class.method = function () {
    // I am a static method
};

For example:

var Example = function () {
    this.name = "DefaultName";
};

Example.prototype.setName = function (name) {
    this.name = name;
}

var test = new Example();
test.setName("foo");

console.log(test.name); // "foo"
Sign up to request clarification or add additional context in comments.

3 Comments

Oh,so fast your answer!Sorry,may be my expression is not clear.What confused me is i think this always refers to an object instance,but Class is not an object instance.
@jlchen yes, actually Class is an object instance. Functions are objects.
Thank you!!! Class is also an object instance of Function i read an article.And i know what is first-class now O(∩_∩)O
0

If you call .method() on your constructor function itself (without new), this will still be bound to the Class object. The this value always depends on the type of invocation, since you are calling the function from within an object (= a method), this will be bound to that context.

Comments

0
Class = function() {
   this.xx = "hello";
}
Class.method = function () { this.xx } 
Class.prototype.method = function () { alert(this.xx) }
var clazz=new Class();
clazz.method(); // display "hello";
Class.method() // undefined

Comments

0

it will refer to the object calling the Class.method function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.