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

  • 相关阅读:
    macOS下查看端口是否被占用命令
    macOS下安装tomcat服务器
    unittest 知识问答题-也许面试会有用-欢迎补充
    python.unittest中常用断言方法
    如何在命令行terminal中运行pycharm项目
    如何保证 软件测试覆盖率
    如何衡量 测试覆盖率
    软件测试全流程 总结
    接口测试对传统测试模型的改进
    关于http/https协议
  • 原文地址:https://www.cnblogs.com/shamgod/p/5523504.html
Copyright © 2011-2022 走看看