zoukankan      html  css  js  c++  java
  • 面向对象的JavaScript-005-Function.prototype.call()的3种作用

    1.

     1 // call的3种作用
     2     // 1.Using call to chain constructors for an object
     3     function Product(name, price) {
     4       this.name = name;
     5       this.price = price;
     6 
     7       if (price < 0) {
     8         throw RangeError('Cannot create product ' +
     9                           this.name + ' with a negative price');
    10       }
    11     }
    12 
    13     function Food(name, price) {
    14       Product.call(this, name, price);
    15       this.category = 'food';
    16     }
    17 
    18     function Toy(name, price) {
    19       Product.call(this, name, price);
    20       this.category = 'toy';
    21     }
    22 
    23     var cheese = new Food('feta', 5);
    24     console.log(cheese);
    25     var fun = new Toy('robot', 40);
    26     console.log(fun);
    27 
    28     // 2.Using call to invoke an anonymous function
    29     var animals = [
    30       { species: 'Lion', name: 'King' },
    31       { species: 'Whale', name: 'Fail' }
    32     ];
    33 
    34     for (var i = 0; i < animals.length; i++) {
    35       (function(i) {
    36         this.print = function() {
    37           console.log('#' + i + ' ' + this.species
    38                       + ': ' + this.name);
    39         }
    40         this.print();
    41       }).call(animals[i], i);
    42     }
    43 
    44     // Using call to invoke a function and specifying the context for 'this'
    45     // In below example, when we will call greet the value of this will be bind to object i.
    46     function greet() {
    47       var reply = [this.person, 'Is An Awesome', this.role].join(' ');
    48       console.log(reply);
    49     }
    50 
    51     var i = {
    52       person: 'Douglas Crockford', role: 'Javascript Developer'
    53     };
    54 
    55     greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer

  • 相关阅读:
    C 库函数 ------ qsort()
    递归之美
    C函数库 ------ ctype.h
    scanf 多行输入判断结束
    POSIX库、glibc库、pthreads库、libc库、newlib、uClibc
    Docker 私有仓库搭建
    在daemon.json中配置主机后无法启动docker
    MySQL配置HeartBeat实现心跳监控和浮动IP
    Heartbeat基础知识-运维小结
    (二) Docker中启动镜像
  • 原文地址:https://www.cnblogs.com/shamgod/p/5523504.html
Copyright © 2011-2022 走看看