Class.method = function () { this.xx }
Class.prototype.method = function () { this.xx }
var clazz = new Class();
clazz.method();当我在函数中调用第四行时,this将引用clazz,但是当执行Class.method()时,this将引用什么?
发布于 2011-12-02 21:45:05
Class.prototype.method函数中的this仍将引用Class实例。这不是一个静态方法,一个静态(即每个类一个)方法应该是这样的:
Class.method = function () {
// I am a static method
};例如:
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"发布于 2011-12-02 21:45:43
如果在构造函数本身上调用.method() (没有new),this仍将绑定到Class对象。this的值总是取决于调用的类型,因为您是从一个对象(=一个方法)中调用函数的,所以this将被绑定到该上下文。
发布于 2011-12-02 21:48:35
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() // undefinedhttps://stackoverflow.com/questions/8357235
复制相似问题