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]

  • 相关阅读:
    Docker
    Docker
    Linux
    VUE- 前端插件
    小程序中实现 input 搜索框功能
    Vue 中用delete方式进行axios请求接口,请求状态码报415(Unsupported Media Type)
    关于小程序使用map组件,标记markers时报错误(ret is not defined)
    关于element 框架中table表格选中并切换下一页之前选中数据消失的问题
    vue切换路由时报错 uncaught(in promise) Navigation Duplicated 问题
    2019-09-09 JS面试题(持续更新中)
  • 原文地址:https://www.cnblogs.com/sanshi/p/1454078.html
Copyright © 2011-2022 走看看