zoukankan      html  css  js  c++  java
  • AOP in JavaScript

    AOP stands for Aspect-oriented programming. I think the main point of this technology is the ability to add code before or after a function execution.

    After some digging on the internet, i write my implement of AOP in JavaScript.

    1. First, see the original functin:

    function hello() {
    for (var i = 0; i < arguments.length; i++) {
    arguments[i] += "[hello]";
    }
    return arguments;
    }
    var args = hello('World', 'JavaScript');
    console.log(Array.prototype.join.apply(args, [' ']));
    // World[hello] JavaScript[hello]

    2. I want to add before aspect function like this:

    aspect.before(window, 'hello', function() {
    for (var i = 0; i < arguments.length; i++) {
    arguments[i] += "[before]";
    }
    return arguments;
    });

    Therefore i give the aspect object like this:

    var aspect = {
    before: function(context, targetName, fn) {
    var target = context[targetName];
    context[targetName] = function() {
    return target.apply(context, fn.apply(context, arguments));
    };
    }
    };

    Now,the result is:

    // World[before][hello] JavaScript[before][hello]

    You can see, the before function has been injected before the original function's execution.

    3. Let's finish the example, add another aspect.after function:
    var aspect = {before: function(context, targetName, fn) {
    var target = context[targetName];
    context[targetName] = function() {
    return target.apply(context, fn.apply(context, arguments));
    };
    },
    after: function(context, targetName, fn) {
    var target = context[targetName];
    context[targetName] = function() {
    return fn.apply(context, target.apply(context, arguments));
    };
    }
    };
    function hello() {
    for (var i = 0; i < arguments.length; i++) {
    arguments[i] += "[hello]";
    }
    return arguments;
    }
    aspect.before(window, 'hello', function() {
    for (var i = 0; i < arguments.length; i++) {
    arguments[i] += "[before]";
    }
    return arguments;
    });
    aspect.after(window, 'hello', function() {
    for (var i = 0; i < arguments.length; i++) {
    arguments[i] += "[after]";
    }
    return arguments;
    });
    var args = hello('World', 'JavaScript');
    console.log(Array.prototype.join.apply(args, [' ']));
    // World[before][hello][after] JavaScript[before][hello][after]

  • 相关阅读:
    Code Forces Gym 100886J Sockets(二分)
    CSU 1092 Barricade
    CodeChef Mahesh and his lost array
    CodeChef Gcd Queries
    CodeChef GCD2
    CodeChef Sereja and LCM(矩阵快速幂)
    CodeChef Sereja and GCD
    CodeChef Little Elephant and Balance
    CodeChef Count Substrings
    hdu 4001 To Miss Our Children Time( sort + DP )
  • 原文地址:https://www.cnblogs.com/sanshi/p/1454078.html
Copyright © 2011-2022 走看看