zoukankan      html  css  js  c++  java
  • 你不知道的JS系列上( 46 ) - 隐式混入

    var Something = {
      cool: function () {
        this.greeting = 'Hello World';
        this.count = this.count ? this.count + 1 : 1;
      }
    }
    Something.cool();
    Something.greeting; // 'Hello World'
    Something.count; // 1
    
    var Another = {
      cool: function() {
        // 隐式把 Something 混入 Another
        Something.cool.call(this);
      }
    };
    Another.cool();
    Another.greeting; // 'Hello World'
    Another.count; // 1

    通过在构造函数调用或者方法调用中使用 Something.cool.call(this); 实际上 “借用” 了函数 Something.cool() 并在 Another 的上下文调用了它。最终的结果是 Something.cool() 中的赋值操作都会应用到 Another 对象。因此,我们把 Something 的行为 “混入” 到了 Another 中。

    虽然这类技术利用了 this 的重新绑定功能,大师 Something.cool.call(this) 仍然无法变成相对而且更灵活的引用,所以使用时千万要小心。通常来说,尽量避免这样的结构,以保证代码的整洁和可维护性。
  • 相关阅读:
    Laravel 中使用支付宝、银联支付、微信支付进行支付
    C# 文件读写系列三
    C# 文件读写系列二
    C# Encoding
    C# 文件操作系列一
    Unity 依赖注入
    控制反转和依赖注入模式
    Aop学习笔记系列一
    C# lambda表达式
    C# 委托基础
  • 原文地址:https://www.cnblogs.com/wzndkj/p/12651165.html
Copyright © 2011-2022 走看看