返回列表

Javascript精华点之closure/proxy

默认分类 2016/03/15 03:47

示例代码如下:

<button type="button" onclick="doit()">doit</button>
<script type="text/javascript">
<!--
function doit() {
    //Todo
    tom.say();
    // >> Tom aged 16
    nancy.say = tom.say;
    nancy.say();
    // >> Tom aged 40
    nancy.say = proxy(tom.say, tom);
    nancy.say();
    // >> Tom aged 16
}
var tom = {
    name: 'Tom',
    age: 16,
    say: function() {
        console.log('>> Tom aged ' + this.age)
    }
};
var nancy = {
    name: 'Nancy',
    age: 40
};

var proxy = function(func, scope) {
    return function() {
        return func.apply(scope, arguments);
    }
};

//-->
</script>