Example of Javascript Duck Typing?

前端 未结 3 1620
無奈伤痛
無奈伤痛 2020-12-13 02:48

Some programmers advise against using pseudo classical inheritance in Javascript, but advise using duck-typing and giving each object a set of capabilities.

Is there

3条回答
  •  执念已碎
    2020-12-13 03:41

    So you have these two functions:

    function make ( props ) {
        var obj = Object.create( {} );
        Object.keys( props ).forEach(function ( key ) {
            obj[ key ] = props[ key ];
        });
        return obj;
    };
    
    function addMethods ( obj, methods ) {
        var proto = Object.getPrototypeOf( obj );
        Object.keys( methods ).forEach(function ( key ) {
            proto[ key ] = methods[ key ];
        });        
    }
    

    Usage:

    var simba = make({
        name: "Simba",
        type: "lion"
    });
    
    addMethods( simba, {
        swim: function () {},
        run: function () {}
    });
    
    addMethods( simba, {
        hunt: function () {},
        kill: function () {}
    });
    

    Live demo: http://jsfiddle.net/UETVc/

提交回复
热议问题