function MyClass(){
this.field1 = "Field in MyClass";
}
MyClass.prototype.print = function() {
console.log("print in MyClass:" + this.field1);
}
function useMyClassPrint() {
var mc = new MyClass();
mc.print();
setTimeout(mc.print, 10);
setTimeout("mc.print()", 10);
}
我得到这些结果:
mc.print(); // this one is easy, it returns "print in MyClass:Field in MyClass"
// but ...
setTimeout(mc.print, 10); // "print in MyClass:undefined" why?!
setTimeout("mc.print()", 10); // runtime error?!@@
function MyClass(){
this.field1 = "Field in MyClass";
}
MyClass.prototype.print = function() {
console.log("print in MyClass:" + this.field1);
}
var mc = new MyClass();
mc.print(); /*ok*/
setTimeout(mc.print, 10); /*it's just a reference to function*/
setTimeout(mc.print.bind(mc),10);/*binded*/
当您定义时
function MyClass(){
this.field1 = "Field in MyClass";
}
字段 1 是在实例化类时设置的。字段 1 不是常量。
在控制台中试用:
MyClass.field1 -> /*undefined*/
new MyClass().field1 -> /*Field in MyClass*/
setInterval(( 函数接收一个函数:
setTimeout(mc.print, 10);
mc.print 只是对函数的引用,没有对"mc"实例的引用。