call方法:调用一个对象的一个方法,以另一个对象替换当前对象。
apply方法:应用某一对象的一个方法,用另一个对象替换当前对象。call与apply的不同就是call传的值可以是任意的,而apply传的剩余值必须为数组。
//---------------------------------------方法一--------------------------------------------------------
<script language="Javascript"><!-- function Class1() { this.name = "class1"; this.aaa = "aaa"; this.showNam = function() { alert(this.name); } } function Class2() { this.name = "class2"; } var c1 = new Class1(); var c2 = new Class2(); //c1.showNam(); c1.showNam.call(c2);//对象置换,针对方法而言 c1.aaa.call(c2);//错误,只能针对方法继承,属性不支持--></script>
//--------------------------------------方法二---------------------------------------------------------
<script type="text/javascript">function People(){this.type = '人';}People.prototype = {getType:function(){console.log(this.type);}};
function Student(name, age){People.call(this, arguments);var fn,sfn=this.constructor.prototype;console.log(sfn);for(fn in People.prototype){if(!sfn[fn]){sfn[fn] = People.prototype[fn];}}this.name = name;this.age = age;this.type = '超人';}Student.prototype = {getAge:function(){console.log(this.age);},getName:function(){console.log(this.name);}};var student = new Student('lily', 100);student.getAge();student.getName();student.getType();
</script>
新闻热点
疑难解答