function test(a){
this.a = a;
}
test.prototype.get = function(){
var obj = document.createElement("div");
obj.style.cssText = "position:absolute; width:200px; height:200px;";
obj.n = 10;
obj.onclick = function(){test.show(this.n);};
}
test.prototype.show = function(b){
alert(b);
}
着色的部分应该如何写,才能正确调用test的show方法呢?

解决方案 »

  1.   

    test.prototype.get里加上var _this = this;然后obj.onclick = function(){_this.show(...)}
      

  2.   

    JS中funtion也可以作为一个类来看待,类当然可以使用new来定义对象了。其次,定义XXX.prototype.YYY  代表在类XXX增加属性YYY  这个YYY可以是基本属性也可以是方法体实现或者方法名都可以,所以可以这样调用:
    var call = new test("test");
    call.show("test1");
    call.get();再举个例子,在JS常规方法中对于String对象没有过滤两段空格的方法,你可以提供一个Util组件去过滤,但是写起来不是那么爽,如果能够使得XXX.trim()岂不是更加好,那么你就在全局定义一个:String.prototype.trim = function(){ 
        return this.replace(/(^\s*)|(\s*$)/g, ""); 
    }这样在其作用域下下的所有字符串对象,都可以使用XXX.trim()了。
      

  3.   


    <html> 
    <head> 
    <title> SCROLL </title> 
    <body> 
      <div id="tt"> </div>
    </body>
    <SCRIPT>
    function test(a){
        this.a = a;
    }
        test.prototype.get = function(){
        var _this=this;
        var obj1=document.getElementById("tt");    var obj = document.createElement("input");
       
        obj.style.cssText = "position:absolute; width:200px; height:200px;";
        obj.n=10;
        obj.value="123123";    obj.onclick = function(){_this.show(this.n);};
        obj1.appendChild(obj);
         }
        test.prototype.show = function(b){
        alert(b);
       }var ttt=new test();
    ttt.get();</SCRIPT></html>