<span style="font-size:18px;"><script>
function Person(name,age){
<span style="white-space:pre"> </span>this.name = name;
<span style="white-space:pre"> </span>this.age = age;
<span style="white-space:pre"> </span>this.print = function(key){
<span style="white-space:pre"> </span>if(!!key){
<span style="white-space:pre"> </span>alert(key+':'+this[key]);
<span style="white-space:pre"> </span>return;
}
<span style="white-space:pre"> </span>for(var o in this){
<span style="white-space:pre"> </span>alert(o+':'+this[o]);
}
}
}
function Student(name,age,grade,school){
<span style="white-space:pre"> </span>this.name = name;
<span style="white-space:pre"> </span>this.age = age;
<span style="white-space:pre"> </span>this.grade = grade;
<span style="white-space:pre"> </span>this.school = school;
}
var person1 = new Person('老王',60);
var student1= new Student('小明',20,'大一','清华大学');
person1. print();
person1.print.apply(student1,['age']);
person1.print.call(student1,'grade','age');
</script>
</span>
执行结果:
name:老王
age:60
print: function(key){
if(!!key){
alert(key+’:’+this[key]);
return;
}
for(var o in this){
alert(o+’:’+this[o]);
}
}
Age:20
Grade:大一
执行顺序:1.执行person1.print:接收传递的name和age。 将name,age和print放到o中遍历输出(因print的key没有接收的值,故将print后的值原样输出)
2. 执行person1.print.apply(student1,[‘age’]); 将student1中的age传参给print(即key),执行print等于的函数,判断有key,输出age
3. 执行person1.print.call(student1,’grade’,’age’); 将student1中的grade和age传参给print(即key,但是key只能接收一个grade值),执行print等于的函数,判断有key,输出grade