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();



  • 相关阅读:
    用例失败重新运行
    pytest启动浏览器,失败用例截图
    解决pycharm问题:module 'pip' has no attribute 'main'
    pytest的HTML
    pytest 的 yield
    pytest的setup和teardown
    pytest的fixture和conftest
    pycharm运行pytest
    简单易用的MongoDB
    快速入门系列--CLR--02多线程
  • 原文地址:https://www.cnblogs.com/unbreakable/p/2437841.html
Copyright © 2011-2022 走看看