• js call


    call 方法
    调用一个对象的一个方法,以另一个对象替换当前对象。

    call([thisObj[,arg1[, arg2[,   [,.argN]]]]])
    参数1:thisObj
    可选项。将被用作当前对象的对象。
    参数2:arg1, arg2, , argN
    可选项。将被传递方法参数序列。
    说明:
    call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
    如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj.

    call 方法在js继承中经常看到,也一直搞不懂,这到底是什么东西,看下面这段代码:

    function Person(name,age) {
    this.name = name;
    this.age = age;
    this.alertName = function() {
    alert(this.name);
    }
    this.alertAge = function() {
    alert(this.age);
    }
    }
    function webDever(name,age,sex) {
    Person.call(this,name,age);//webDever继承了Person类
    this.sex = sex;
    this.alertSex = function(){
    alert(this.sex);
    }
    }
    
    var test = new webDever("的闪光灯时",28,"female");
    test.alertName();
    
    test.alertAge();
    
    test.alertSex();

    Person.call(this,name,age) 的 意思就是使用 Person对象代替this对象,那么 webDever中不就有Person的所有属性和方法了吗,test对象就能够直接调用Person的方法以及属性了;

    说的再明白一点,就是相当于将webDever中的Person.call(this,name,age)这部分代码替换为Person类的:

    this.name = name;
    this.age=age;
    this.alertName = function(){
     alert(this.name);
    }
    this.alertAge = function(){
     alert(this.age);
    }

    这样webDever类就相当于:

    function webDever(name,age,sex){
       this.name = name;
       this.age=age;
       this.alertName = function(){
        alert(this.name);
       }
       this.alertAge = function(){
        alert(this.age);
       }
    
       this.sex=sex;
       this.alertSex = function(){
        alert(this.sex);
       }
      }
      var test= new webDever(“愚人码头”,28,”男”);
      test.alertName();//愚人码头
      test.alertAge();//28
      test.alertSex();//

     来自:http://www.css88.com/archives/1692

  • 相关阅读:
    设计模式之单例模式
    设计模式之组合模式
    SVN搭建简单教程
    添加Silverlight应用到HTML
    动态修改配置文件
    Ajax
    jQuery 事件方法
    Java和JavaScript对账户实现掩码并四个一组分隔
    一种简单实现当前时间是否在工作时间内的方法
    Postman接口自动化测试实例用到的完整的SM2前端加密算法代码
  • 原文地址:https://www.cnblogs.com/emmalai/p/5762266.html
Copyright © 2020-2023  润新知