Is there a “right” way to do inheritance in JavaScript? If so, what is it?

后端 未结 5 863
再見小時候
再見小時候 2021-02-02 02:32

I have been trying to learn how to add testing to existing code -- currently reading reading Working Effectively With Legacy Code. I have been trying to apply some of the princ

5条回答
  •  太阳男子
    2021-02-02 03:07

    You are looking at two different things.

    First you have interfaces. The most accepted way of implementing this is though Duck Typing ("if it looks like a duck and quacks like a duck then it is a duck"). This means that if an object implements a set of methods of the interface then it is that interface. You implement this by having an array of method names that define an interface. Then to check if an object implements that interfece you see if it implements those methods. Here is a code example I whipped up:

    function Implements(obj, inter)
    {
        var len = inter.length, i = 0;
        for (; i < len; ++i)
        {
            if (!obj[inter[i]])
                return false;
        }
        return true;
    }
    
    var IUser = ["LoadUser", "SaveUser"];
    
    var user = {
            LoadUser : function()
            {
                alert("Load");
            },
    
            SaveUser : function()
            {
                alert("Save");
            }
        };
    
    var notUser = {
            LoadUser : function()
            {
                alert("Load");
            }
        };
    
    alert(Implements(user, IUser));
    alert(Implements(notUser, IUser));
    

    Now you have inheritance. JS has no inheritance built in; so you have to implement it manually. This is just a matter of "copying" the properties of one object to another. Here is another code sample (not perfect but it demonstrates the point):

    function InheritObject(base, obj)
    {
        for (name in base)
        {
            if (!obj[name])
                obj[name] = base[name];
        }
    }
    
    var Base = {
            BaseFunc : function() { alert("BaseFunc from base"); },
            InheritFunc : function() { alert("InheritFunc from base"); }
        }
    
    var Inherit = {
            InheritFunc : function() { alert("InheritFunc from inherit"); },
            AnotherFunc : function() { alert("AnotherFunc from inherit"); }
        }
    
    InheritObject(Base, Inherit);
    
    Inherit.InheritFunc();
    Inherit.BaseFunc();
    Inherit.AnotherFunc();
    
    Base.BaseFunc();
    Base.InheritFunc();
    

    You probably want to look at http://www.mootools.net. It has my favorite implementation of Classes. You also definitely want to check out "Pro Javascript Design Patterns"

    http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X

    This book goes into good detail about how to emulate OOP in javascript.

提交回复
热议问题