`
b_l_east
  • 浏览: 636849 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

JavaScript 函数、类、对象、方法、属性 之 函数和类的关系

阅读更多

因为函数和类的定义是一样的,那么函数可以当类用,类也可以当函数用。

例如:

//方法和类的定义
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指的是实例对象。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics