简体   繁体   English

扩展Javascript原型方法

[英]Extending Javascript prototype methods

I am having a hard time understanding how this preserves a function an essentially extends it. 我很难理解这如何保留功能并从本质上扩展了它。

I see that (function(){}) will call a declared function immediately. 我看到(function(){})将立即调用一个声明的函数。 I don't understand what supplying open as a parameter. 我不明白什么提供open作为参数。 Finally, I don't understand what goes on with (XMLHttpRequest.prototype.open) . 最后,我不明白(XMLHttpRequest.prototype.open)发生了什么。 Is this calling the prototype function? 这是调用原型函数吗?

(function(open) {
  XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
    open.call(this, arguments);
  };
})(XMLHttpRequest.prototype.open);

function (open) { .. } declares a function which takes one argument. function (open) { .. }声明一个带有一个参数的函数。
(..)(XMLHttpRequest.prototype.open) is calling this function and is passing the open function of XMLHttpRequest.prototype as argument. (..)(XMLHttpRequest.prototype.open)正在调用此函数,并将XMLHttpRequest.prototypeopen函数作为参数传递。 Yes, it's passing the actual function itself; 是的,它正在传递实际的函数本身; functions can be passed around like values. 函数可以像值一样传递。

So, inside that IIFE (immediately invoked function expression), open is the original implementation of XMLHttpRequest.prototype.open . 因此,在该IIFE(立即调用的函数表达式)内部, openXMLHttpRequest.prototype.open的原始实现。

Then, inside the IIFE, XMLHttpRequest.prototype.open gets replaced with a new function. 然后,在IIFE中,将XMLHttpRequest.prototype.open替换为新函数。 Inside that new function, the original open function gets called. 在该新函数内部,将调用原始的open函数。 This by itself isn't too exciting, but it shows how you could wedge in your own code between XMLHttpRequest.prototype.open being called and the actual, original open function being executed. 这本身并不太令人兴奋,但是它说明了如何在调用XMLHttpRequest.prototype.open和执行实际的原始open函数之间插入自己的代码。

The whole ordeal with the IIFE is just to preserve a handle to the original open function which cannot be overwritten by other code under any circumstances, because it's local to a function. 使用IIFE的整个过程只是为了保留原始open函数的句柄,该句柄在任何情况下都不能被其他代码覆盖,因为它是函数的局部特性。

This is exact replica of this. 这是它的精确副本。

//Create a XMLHttpRequest.realOpen function and store the original XMLHttpRequest.open function in it
XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open;

//Change the XMLHttpRequest.open function
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {

    //Do Your Code Here....

    //Call original XMLHttpRequest.open function which is now saved in XMLHttpRequest.realOpen function
    this.realOpen(method, url, async, user, password);
};

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

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