zoukankan      html  css  js  c++  java
  • 【JavaScript】 使用extend继承对象的prototype方法

      之前有学习过通过prototype模式来构造类,并通过prototype来添加方法。好处大概有以下几点:

        1.类方法可以都放在prototype中,可以提高性能效率。

        2.可以用prototype来实现继承。

      但是缺点也不少,比如:

        1.通过prototype添加方法又臭又长,编码很不方便。

            2.继承对象时,整个继承方法比较复杂,不容易实现。

          一番研究后,发现backbonejs中的继承非常方便,因此想学习一下。

      backbone中的继承是基于_.extend对prototype方法进行合并。

        // _就是underscore,如果项目没有引进underscore,那么用$.extend替代也是一样的。

      比如有一个base类:

    var base = function(){}
    
    // 添加prototype方法时,并不是直接添加
    // 比如base.prototype.init = function(){}
    // 而是通过下面下方进行添加
    $.extend(base.prototype,{
        init:function(){},
        setSetting:function(){}
    });

      然后有一个sub类,继承base类。

    var sub = function(){}
    
    // 先用sub的自定义方法来合并base的prototype,再用base.prototype合并sub.prototype,最后返回的是最终的sub.prototype
    $.extend(sub.prototype,base.prototype,{
      construcotr:sub, onclick:function(){} });
  • 相关阅读:
    LeetCode-860. Lemonade Change
    LeetCode-455.Assign Cookies
    LeetCode-122.Best Time to Buy and Sell Stock II
    LeetCode-438.Find All Anagrams in a String
    LeetCode-50.Pow(x,n)
    LeetCode-236.Lowest Common Ancestor of a Binary Tree
    LeetCode-235.Lowest Common Ancestor of a Binary Search Tree
    LeetCode-98.Validate Binary Search Tree
    LeetCode-18.4Sum
    LeetCode-15.3Sum
  • 原文地址:https://www.cnblogs.com/nonkicat/p/6322177.html
Copyright © 2011-2022 走看看