zoukankan      html  css  js  c++  java
  • javascript继承call()和apply实现继承

      call方法是Function对象中的方法,因此我们定义的每个函数都拥有该方法。可以通过函数名来调用call方法,call方法的第一个参数会被传递给函数中的this,从第2个参数开始,挨个赋值给函数中的参数

    function person(name){
    alert(name+" : "+this.hobby);
    }
    var obj=new Object();
    obj.hobby="打酱油";
    person.call(obj,"小张");


    (2)

     1 <script language="javascript" type="text/javascript">
    2 function Parent(name){
    3 this.name=name;
    4 this.sayHello=function(){
    5 alert(this.name);
    6 }
    7 }
    8 function Child(name,hobby){
    9 this.hobby=hobby;
    10 Parent.call(this,name);
    11 this.say=function(){
    12 alert(this.name+" : " +this.hobby);
    13 }
    14 }
    15 var ch=new Child("小明","打酱油");
    16 ch.sayHello();
    17 ch.say();
    18 </script>

    apply方法实现继承

     1     
    2 function Parent(name){
    3 this.name=name;
    4 this.sayHello=function(){
    5 alert(this.name);
    6 }
    7 }
    8 function Child(name,hobby){
    9 this.hobby=hobby;
    10
    11 Parent.apply(this,[name]/* 或者new Array(name) */);
    12 this.say=function(){
    13 alert(this.name+" : "+this.hobby);
    14 }
    15 }
    16 var ch=new Child("小明","打酱油");
    17 ch.sayHello();
    18 ch.say();



  • 相关阅读:
    64最长和谐子序列(594)
    63找到字符串中所有字母异位词(438)
    62有效的数独(36)
    10.10
    9.27作业
    9.27
    9.26
    9.25
    9.18学习内容
    9.17作业
  • 原文地址:https://www.cnblogs.com/unbreakable/p/2437841.html
Copyright © 2011-2022 走看看