zoukankan      html  css  js  c++  java
  • 对apply和call的理解

      apply和call都是可以改变this上下文的方法,从而可以达到实现继承的目的。两者的功能完全一样,只是传入的参数略有不同。

    apply: apply(this,[arg1,arg2,arg3...])

    call: call(this,arg1,arg2,arg3....)

    但是声明一下,这里所谓的继承,是继承类的构造函数内的属性和方法,外部对类添加的属性和方法,使用apply和call是不会继承上的。来看一个demo:

     1 function Animal(name,age){
     2     this.name=name;
     3     this.age = age;
     4     this.getName = function(){
     5         return this.name;
     6     }
     7     this.setName = function(name){
     8         this.name = name
     9     }
    10 }
    11 Animal.getAge = function(){
    12     return this.age;
    13 }
    14 
    15 function Dog(){
    16     Animal.apply(this,arguments);//Dog类继承了Animal类,这时Dog的实例就拥有了Animal构造器内部的属性和方法
    17 }
    18 var dd = new Dog('maomao',10)
    19 alert(dd.getName());//继承了父类的方法 输出:maomao
    20 alert(dd.getAge());//继承不了除构造方法以外的属性和方法 此处报错
  • 相关阅读:
    5G名词术语
    什么是IPv6
    如何用SecureCRT 登录eNSP模拟器里的设备
    numpy-排序
    numpy-tile 数组复制
    经纬度计算距离与方位角
    numpy-添加操作大全
    高效编程之 concurrent.future
    linux命令 集合
    PostgreSQL-表空间
  • 原文地址:https://www.cnblogs.com/freefish12/p/5561368.html
Copyright © 2011-2022 走看看