zoukankan      html  css  js  c++  java
  • js中使用使用原型(prototype)定义方法的好处

    经常在前端面试或是和其他同行沟通是,在谈到构造在JS定义构造函数的方法是最好使用原型的方式:将方法定义到构造方法的prototype上,这样的好处是,通过该构造函数生成的实例所拥有的方法都是指向一个函数的索引,这样可以节省内存。

    当然,这种说法没有任何问题,只是在实现上,并非只有使用prototype的方式才能达到这样的效果,我们可以将方法以函数的形式定义在构造函数之外,然后在构造函数中通过this.method = method的方式,这样生成的实例的方法也都通过索引指向一个函数,具体如下:

    // 不使用原型定义方法:
    (function() {
        function Constractor() {
            this.method1 = method1;
            this.method2 = method2;
        }
    
        function method1() {
        }
    
        function method2() {
       }
    })();

    一般使用原型定义时代码如下:

    (function () {
        function Constractor() {
        }
    
        Constactor.prototype = {
            method1: function() {
            },
            method2:  function() {
            }
        };
        
        // 或者
        Constactor.prototype.method1 = function() {
        };
        Constactor.prototype.method2 = function() {
        };
    
    })();

    理论和实现都没有什么高深的,只是为了达到同样的目的,可以通过不同的途径,只是此种方式在使用instanceOf运算符来判断继承关系时就不奏效了。

  • 相关阅读:
    动态传参
    函数的介绍
    文件的操作
    send email with formatted table
    minimize and close window with customed winform
    python algorithm
    something important about docker
    book list
    which language is suitable for what to do
    Find Duplicate Items in list fast
  • 原文地址:https://www.cnblogs.com/yunfour/p/3946444.html
Copyright © 2011-2022 走看看