下面这段代码:
function Person(name,age){
    this.name=name;
    this.age=age;
    this.sayHello=function(){
        alert("Hi,I am "+name);
    }
}
function Print(){
    this.functionName="Print";
    var meg=[];
    this.show=function(){
        for(var key in this){
            if(typeof(this[key])!="function"){
              meg.push([key,":",this[key]].join(" "));
            }
        }
        alert(meg.join(","));
    }
}
function Student(names,ages,grade,school){
    Person.apply(this,arguments);
    Print.apply(this,arguments);
    this.grade=grade;
    this.school=school;
}
var s1=new Student(' sean ',23,4,"YanTai");
alert(s1.name);
s1.show();
s1.sayHello();Student实例s1本来没有方法,但是用apply方法之后就有了方法和Person、Print的属性。
我疑问的是:s1如何知道将names赋值给name属性,将ages赋值给age属性呢?

解决方案 »

  1.   

    this.apply这个等于是方法的调用的。
    就是调用了你父类的构造函数了。你传的参数不是有顺序吗?那不是根据你的顺序来的赋值的。
      

  2.   

    多谢你。我再问一个问题,apply接受的第一个参数,这个作用域,它的作用是啥啊?
      

  3.   


    强制更改作用域,用来更改其内部的this指向。看以下几个简单的小例子,大概就清楚了
     
       var a={
        b:1,
        c:function(){
            alert(this.b);//这个this原本是指向a的,a.b=1,所以直接调用应该返回1
        }
     };
     var b=3333;//在window域下定义了一个b
     a.c();//直接谳用:1
     a.c.apply(this);//将a.c内部的this指向window,则this.b==window.b==3333
     var d={
        b:'我是d中的b'
     };
     a.c.apply(d);//将a.c内部的this指向对象c,则this.b==d.b=='我是d中的b'
      

  4.   

    上面最后一行打错个字母:将a.c内部的this指向对象d,则this.b==d.b=='我是d中的b'
      

  5.   

    看看这段程序在后台是如何执行的:
    文件名保存为apply.asp 或 apply.aspx 均可:<%@ LANGUAGE='JAVASCRIPT' %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    </head>
    <body>
    <%
    function Person(name,age){
        this.name=name;
        this.age=age;
        this.sayHello=function(){
            Response.Write("<br>Hi,I am "+name);
        }
    }
    function Print(){
        this.functionName="Print";
        var meg=[];
        this.show=function(){
            for(var key in this){
                if(typeof(this[key])!="function"){
                  meg.push([key,":",this[key]].join(" "));
                }
            }
            Response.Write("<br>"+meg.join(","));
        }
    }
    function Student(names,ages,grade,school){
        Person.apply(this,Student.arguments);
        Print.apply(this,Student.arguments);
        this.grade=grade;
        this.school=school;
    }
    var s1=new Student(' sean ',23,4,"YanTai");
    Response.Write("<br>"+s1.name);
    s1.show();
    s1.sayHello();%>
    </body>
    </html>