JS Implementation AOP

Source: Internet
Author: User

JS Implementation AOP

<script>
function Actsasaspect (obj,handlers) {
if (typeof obj = = ' function ') {
obj = Obj.prototype;
}

for (var methodName in handlers) {
var _handlers = Handlers[methodname];
For (var handler in _handlers) {
if (handler = = ' Before ' | | handler = = ' after ') && typeof _handlers[handler] = = ' function ') {
Eval_r (Handler) (Obj,methodname,_handlers[handler]);
}
}
}

function before (obj,method,f) {
var original = Obj[method];
Obj[method] = function () {
F.apply (this, arguments);
Return original.apply (this, arguments);
}
}

function after (Obj,method, f) {
var original = Obj[method];
Obj[method] = function () {
Original.apply (this, arguments);
Return f.apply (this, arguments);
}
}
}

Actsasaspect (test,{' say2 ': {before:function () {alert (' before ');},after:function () {alert (' after ');}});

FunctionTest () {}

Actsasaspect (test,{' say2 ': {before:function () {alert (' before ');},after:function () {alert (' after ');}});

Test.prototype.say2 = function (s) {
alert (s);
}

Actsasaspect (test,{' say2 ': {before:function () {alert (' before ');},after:function () {alert (' after ');}});

var t = newtest ();

Actsasaspect (t,{' say2 ': {before:function () {alert (' before ');},after:function () {alert (' after ');}});
T.say2 ("Hello2");

</script>

Because Sina's editor is too poor, to change the Eval_r to Eval can be run

Support for class and object two types of AOP, which is based on modifications to the prototype, which are method modifications to the object

JS Implementation AOP

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.