下面这段代码:
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属性呢?
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属性呢?
就是调用了你父类的构造函数了。你传的参数不是有顺序吗?那不是根据你的顺序来的赋值的。
强制更改作用域,用来更改其内部的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'
文件名保存为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>