开发者

Javascript Plugin Development , Extending Libraries

开发者 https://www.devze.com 2023-01-20 10:15 出处:网络
i got two javascript objects api and myApi : var api = {}; api.foo = function(){ ... }; api.foo2 = function(){ ... };

i got two javascript objects api and myApi :

var api = {};
api.foo = function(){ ... };
api.foo2 = function(){ ... };

var myApi = {};
myApi.foo = function(){ ...};
myApi.myFoo = function(){ ...};
myApi.myFoo2 = function(){ ...};

i want to add all myApi.* functions to api object without overriding api.foo.

In开发者_如何学Cdeed, i want learn how to extend APIs to each other and developing plugins with javascript.

What are the best practices in this subject?


To answer the first part of your question, you can modify the merge method I use in some of my code:

if (typeof Object.merge !== 'function') {
    Object.merge = function (o1, o2) { // Function to merge all of the properties from one object into another
        for(var i in o2) { o1[i] = o2[i]; }
        return o1;
    };
} 

To not overwrite preexisting objects, you would have to add a check:

if (typeof Object.merge !== 'function') {
    Object.merge = function (o1, o2) { // Function to merge all of the properties from one object into another
        for(var i in o2) { if(!(i in o1)) o1[i] = o2[i]; }
        return o1;
    };
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消