阳光博文 你的空间 知识的容器

在JavaScript中使用AOP

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script>
        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 voice() {
            alert("救命啊!");
        }
        aspect.after(window, 'voice', function () { alert("help"); })

    </script>
</head>
<body>


    <input type="button" id="btn" value="动我就叫人来" onclick="voice()">
</body>
</html>


在线咨询