zoukankan      html  css  js  c++  java
  • JavaScript——call() 方法

    function Product(name, price) {
      this.name = name;
      this.price = price;
    }
    function Food(name, price) {
      Product.call(this, name, price);
      this.category = 'food';
    }
    function Toy(name, price) {
      Product.call(this, name, price);
      this.category = 'toy';
    }
    var cheese = new Food('feta', 5);
    var fun = new Toy('robot', 40);

    1、使用 call 方法调用父构造函数

           在一个子构造函数中,你可以通过调用父构造函数的 call 方法来实现继承,类似于 Java 中的写法。下例中,使用 Food 和 Toy 构造函数创建的对象实例都会拥有在 Product 构造函数中添加的 name 属性和 price 属性,但 category 属性是在各自的构造函数中定义的。

    2、语法

    fun.call(thisArg, arg1, arg2, ...)

    1)参数:

    thisArg

         在 fun 函数运行时指定的 this 值。if(thisArg == undefined|null) this = window,if(thisArg == number|boolean|string) this == new Number()|new Boolean()| new String()

    arg1, arg2, ...

         指定的参数列表。

    2)返回值:

         使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined

    3)描述:

    call() 允许为不同的对象分配和调用属于一个对象的函数/方法。

    call() 提供新的 this 值给当前调用的函数/方法。你可以使用 call 来实现继承:写一个方法,然后让另外一个新的对象来继承它(而不是在新对象中再写一次这个方法)。

  • 相关阅读:
    学习进度第三周
    四则运算3
    学习进度第二周
    单元测试
    四则运算2
    学习进度第一周
    四则运算1
    构建之法阅读笔记01
    linux: 讨论一下网络字节序--------大端与小端的差别
    linux编程:线程条件同步
  • 原文地址:https://www.cnblogs.com/sylys/p/11641528.html
Copyright © 2011-2022 走看看