在这里分享一下我对jscript的面对象编程的一些认识和一点解决方案。jscript和javascript差不多(当然有所不同),但本文中讲到的内容也可用于javascript
jscript支持面对象的一些属性,但他的this指针很奇怪,当有一个对象obj1中的一个成员函数用到this,如果有别一个对象obj2引用该函数,那这个this指向的不是obj1,而是obj2。
下面我们来看一个例子:
<html><head><meta http-equiv="content-type" content="text/html; charset=gb2312"><title>无标题文档</title></head>
<body>
<p id="text">this is the element "p"</p>
<script language="jscript">
function obj1(){ //类obj1
this.innertext = "this is obj1";
}
function obj1.prototype.fun(){
alert(this.innertext);
}
var o1 = new obj1; //对象o1
o1.fun(); //显示“this is obj
text.onclick = o1.fun; //把对象o1的成员函数绑定到html元素text中,这是再点击“this is the element “p”。你会发现显示的是this is the element “p”,而不是this is obj1。
</script>
</body></html>