日期:2014-05-16 浏览次数:20496 次
因为函数和类的定义是一样的,那么函数可以当类用,类也可以当函数用。
例如:
//方法和类的定义
function MyFunc(a, b, c) {
this.pa = a;
this.pb = b;
var pc = c;
this.showInfo = function() {
document.writeln("this: " + this);
document.writeln("pa: " + this.pa);
showSome();
}
function showSome() {
document.writeln("pc: " + pc);
document.writeln("pb: " + this.pb);
}
document.writeln("<h3>这是方法内部的内容</h3>");
return this;
}
//当方法调用
document.writeln(MyFunc(1, 2, 3));
//当类使用
var inst = new MyFunc(1, 2, 3);
inst.showInfo();
document.writeln(inst.pa);
?
输出结果为:
这是方法内部的内容 [object Window] 这是方法内部的内容 this: [object Object] pa: 1 pc: 3 pb: 2 1
? 由此可以看出,当方法调用时this指的是window对象。当类使用时,this指的是实例对象。