如何包装函数但保留其属性?

时间:2015-06-18 17:07:59

标签: javascript

示例代码:

// some library defines a function:

var func1 = function() {
    console.log('i am func1');
}

func1.magicProperty = 'bacon'; // with some properties


// i want to wrap the function to add some extra functionality:

(function() {
    var original = func1;

    func1 = function() {
       var result = original.apply(this,arguments);
        console.log('after func1');
        return result;
    };
})();


func1(); // yay it works!
console.log(func1.magicProperty); // but the properties are missing!!

如何扩展/包装func1但保留其所有属性?我是否必须将它们全部复制到我的新定义中,还是有更好/更快的方式?

这与扩展[class]对象并不完全相同,因为此处没有使用new

1 个答案:

答案 0 :(得分:1)

试试这个

// some library defines a function:
var func1 = function() {
    console.log('i am func1');
}
func1.magicProperty = 'bacon'; // with some properties
// i want to wrap the function to add some extra functionality:
(function() {
    var original = func1;
    func1 = function() {
        var result = original.apply(this,arguments);
        console.log('after func1');
        return result;
    };
    for(var prop in original)
        func1[prop] = original[prop];
})();
func1(); // yay it works!
console.log(func1.magicProperty); // it will print 'bacon'

这是一种复制

在JavaScript中还有一些更复杂的技术称为“原型”链接

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

中的示例

从您的示例中,使用原型

var func1 = function() {
    console.log('i am func1');
}
func1.magicProperty = 'bacon'; // with some properties
func1 = function() {
  var result = original.apply(this,arguments);
  console.log('after func1');
  return result;
}.prototype = func1;
func1();
console.log(func1.magicProperty);

此处}。原型= func1; 立即被调用,因为 func1 将被覆盖