JS Method Proxy

Source: Internet
Author: User

Jiang, Jilin

JS as a scripting language, very easy to get started. With its flexibility, you can easily extend functionality. Today, we will talk about the method of JS proxy. Method proxies are a common form of method extension in scripting languages. The advantage of this flexible form is that when complex JS code needs to be extended, it can be extracted and modified relatively simply. However, its shortcomings are also very obvious, will cause the fragmentation of the code, and thus a double-edged sword.

Basic form

var _func = Obj.func;

Obj.func = function () {

return _func ();

};

Here, the Func method of obj is the original method. We use a _func variable to save the method, and then override the Func method to return the original method that was called. Quite a good understanding.

Indefinite length parameter

Sometimes, we encounter the form of indefinite long parameters. Then we can make the following changes:

var _func = Obj.func;

Obj.func = function () {

Return _func.apply (this, arguments);

};

Written here, the two forms of the JS method agent have been finished. At this point, you may wonder what the use of this method agent is? So, let me take a look at a few examples:

overriding static methods

For some reason, we need to print data to the user help statistics on the specified server at the same time as the console prints. In the process of development, the original ecological Console.log method is used directly to output. Then we can make the following changes.

First, build the Proxy method:

var _log = Console.log;

Console.log = function () {

Return _log.apply (this, arguments);

};

Next, insert the Ajax invocation logic:

Console.log = function () {

var _args = Array.prototype.slice.call (arguments);

$.post ("Srvaddr", {userid:userid, args: _args});

Return _log.apply (this, arguments);

};

The effect can be easily foreseen:



Prototype Agent

Sometimes, we need to take a direct approach to a class. So correspondingly, we are going to be acting on the methods in their prototype. Now let's assume that you want to make array default to support numeric sorting:

var _sort = Array.prototype.sort;

Array.prototype.sort = function () {

_sort.apply (this, arguments);

};

We first detect if the elements in the array are numbers, and if so, sort by numbers, otherwise they will be sorted by default:

var _sort = Array.prototype.sort;

Array.prototype.sort = function () {

var _isnum = true;

for (var i = 0; i < this.length; i + = 1) {

if (typeof This[i]!== "number") {

_isnum = false;

Break

}

}

if (_isnum) {

Return _sort.call (this, function (a, b) {

return a-B;

});

} else {

Return _sort.apply (this, arguments);

}

};

Original sort (convert number to character sort)

Post-agent sort mode

Note: This is only an example of a prototype method proxy. In the actual development, should try to avoid the original object prototype method to do proxy.

Overload

In jquery, the toggle method has multiple overloads, one of which is toggle (display), which determines whether the element is displayed or hidden by accepting the Boolean parameter. This parameter is not accepted by the Fadetoggle method. Let's make a simple proxy that supports the Boolean parameter:

var _fadetoggle = $.fn.fadetoggle;

$.fn.fadetoggle = function (display) {

if (arguments.length = = = 1 && typeof display = = = "Boolean") {

if (display) {

return This.fadein ();

} else {

return This.fadeout ();

}

}

Return _fadetoggle.apply (this, arguments);

};

Determines whether the Fadein or Fadeout method is called by the parameter length and the receive parameter type type. If it does not match, the original Fadetoggle method is called. And so on, Slidetoggle can also be applied.

* Inheritance

In succession, we sometimes need to invoke the parent class method to implement it. This is somewhat similar to the super in Java. A simple example. We define a person that can be laugh. Also define a robot inheritance, which is the laugh of the person who inherits it, but modifies it slightly:

var person = function () {

THIS.name = "";

This.laugh = function () {

Return "Ha ha!";

};

return this;

};

var Robot = function () {

Person.apply (this);

var _laugh = This.laugh;

This.laugh = function () {

return encodeURIComponent (_laugh ());

};

return this;

};

Hijacked

When it comes to hijacking, it's tied to security. Most Web sites today are used to developing with an open source JS library, but if it happens to be plugged into malicious code, then security becomes unsafe (such as a large number of unverified browser plugins in chrome). Below, we will cite several examples of hijacking.

Ajax hijacking

Many people think that storing important user parameters in scope (such as dynamically generated SecureID) by means of closures would be sufficient even if the malicious code was inserted that could not be obtained, thus making it impossible to forge an AJAX request to obtain important information. But what if the entire AJAX request is intercepted?

var _ajax = $.ajax;

$.ajax = function () {

var $p = _ajax.apply ($, arguments);

$p. Done (function (data) {

Do something ...

});

return $p;

};

All AJAX requests (Get,post,getjson) in jquery are eventually called $.ajax to be implemented. The $.ajax method is directly hijacked by the method agent and returns a normal promise object, which makes the page script run without effect. But in fact the data has been hijacked away.

Array hijacking

Array has many prototype methods, such as Push,pop,shift,unshift and so on. We can intercept the data simply by simply acting on an array of proxies.

var _push = Array.prototype.push;

Array.prototype.push = function () {

Do something ...

Return _push.apply (this, arguments);

};

Well, this is the way the agent introduced. Because method proxies confuse code logic, the code structure becomes difficult to understand. In the daily development process, we should try to avoid using it. Use it only if the agent overloads, or changes some of the logic of the hard-to-understand legacy code. So as to avoid the double-edged sword accidentally hurt himself.


JS Method Proxy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.