简体   繁体   English

JavaScript和扩展的第三方API

[英]JavaScript and extending 3rd party API

I'm updating my knowledge about JavaScript and I stuck on one lesson task. 我正在更新有关J​​avaScript的知识,并且坚持了一项课程任务。 I have API that is returning string... 我有API返回字符串...

API.workerName = function (worker) {
   return worker.firstName + ' ' + worker.lastName;
};

The task is to prefix returning string and not change API, but extend it. 任务是给返回的字符串加上前缀,而不更改API,而是对其进行扩展。 I also have to avoid copying & pasting code, because 3rd party code can change. 我还必须避免复制和粘贴代码,因为第三方代码可以更改。 I should re-use it instead. 我应该重新使用它。 What I did is change this function after loading API... 我所做的是在加载API后更改此功能...

API.workerName = function (worker) {
   return '(' + worker.position + ') ' + worker.firstName + ' ' + worker.lastName;
};

... but I think I did it wrong. ...但是我认为我做错了。

To extend the method, you should save the old definition and call it from your extension: 要扩展该方法,您应该保存旧定义并从扩展名中调用它:

API.oldWorkerName = API.workerName;
API.workerName = function(worker) {
    return '(' + worker.position + ')' + API.oldWorkerName(worker);
};

Or maybe this is what your lesson is looking for: 也许这是您的课程正在寻找的内容:

API.workerPositionAndName = function(worker) {
    return '(' + worker.position + ')' + API.workerName(worker);
};

Another neat way to save the old definition and also make it unavailable to anybody else, would be to do something like this using IIFE to create a closure: 保存旧定义并使其对其他任何人都不可用的另一种好方法是使用IIFE创建闭合来进行以下操作:

API.workerName = (function() {
    var old = API.workerName;     // this old version is only available inside your new function
    return function(worker) {
        return '(' + worker.position + ')' + old(worker);
    }
})();

Here's an example: 这是一个例子:

 API = { workerName: function (worker) { return worker.firstName + ' ' + worker.lastName; } }; API.workerName = (function () { var old = API.workerName; return function (worker) { return '(' + worker.position + ')' + old(worker); }; })(); alert(API.workerName({firstName: "Joe", lastName: "Blogs", position: "Lackey" })); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM