reusable javascript objects, prototypes and scope

后端 未结 2 605
说谎
说谎 2021-01-31 06:41
MyGlobalObject;

function TheFunctionICanUseRightAwaySingleForAllInstansesAndWithoutInstanse() {
    function() {
        alert(\'NO CONSTRUCTOR WAS CALLED\');
    }
};
         


        
2条回答
  •  无人及你
    2021-01-31 07:10

    I usually settle with returning an object with functions as properties:

    var newCat = function (name) {
    return {name: name, purr: function () {alert(name + ' purrs')}};
    };
    
    var myCat = newCat('Felix');
    myCat.name; // 'Felix'
    myCat.purr(); // alert fires
    

    You can have inheritance by calling the newCat function and extend the object you get:

    var newLion = function (name) {
        var lion = newCat(name);
        lion.roar = function () {
            alert(name + ' roar loudly');
        }
        return lion;
    }
    

    If you want a global cats object:

    var cats = (function () {
    
    var newCat = function (name) {
        return {
            name: name,
            purr: function () {
                alert(name + ' is purring')
            }
        };
    };
    
    return {
        newCat: newCat
    };
    }());
    

    Now you can call:

    var mySecondCat = cats.newCat('Alice');
    

提交回复
热议问题