gpt4 book ai didi

Javascript函数重载,请解释John Resig(Jquery方式)文章

转载 作者:行者123 更新时间:2023-12-02 16:32:33 25 4
gpt4 key购买 nike

我理解基于参数对象或通过显式检查参数的类型和长度来实现 JavaScript 重载。请解释一下这篇文章:http://ejohn.org/blog/javascript-method-overloading/

最佳答案

下面的函数中有两个概念,我认为这可能是您感到困惑的根源。

下面的代码创建的日志记录应该可以帮助您了解发生了什么。

// addMethod - By John Resig (MIT Licensed)
function addMethod(object, name, fn) {
var old = object[name];
object[name] = function() {
if (fn.length == arguments.length) {
console.log('Arguments and parameters count are the same, found the function');
return fn.apply(this, arguments);
}
if (typeof old == 'function') {
console.log('Arguments and parameters count are not the same, try the next function in the closure stack');
return old.apply(this, arguments);
}
};
}

function Users() {
// This will be at the bottom of the stack, every call will have to go through the functions below
addMethod(this, "find", function() {
console.log('Called with 0 arguments');
});
// This will be at the middle of the task
addMethod(this, "find", function(name) {
console.log('Called with one argument');
});
// This is the one with the least overhead
addMethod(this, "find", function(first, last) {
console.log('Called with two arguments');
});
}

var users = new Users();
users.find();
users.find('John');
users.find('John', 'Resig');

在尝试理解函数时,请记住逐步了解它们。右键单击下面的图片并选择“在新选项卡中打开图片”

Closure stack

这里的 addMethods 会减少一点开销,恕我直言,语法更好,重复更少。

// addMethods - By Juan Methods, inspired by John Resig (MIT Licensed)
function addMethods(object, name /* fn, fn, fn ... */ ) {
// Key is the parameter count for each passed in function, value is the function itself */
var functionMap = {};
for (var i = 2; i < arguments.length; i++) {
functionMap[arguments[i].length] = arguments[i];
}

object[name] = function() {
functionMap[arguments.length].apply(this, arguments);
};
}

function Users() {
// Now every function has constant overhead of a single map lookup, which
// is less expensive than multiple method calls up the closure stack
addMethods(this, "find",
function() {
console.log('Called with 0 arguments');
},
function(name) {
console.log('Called with one argument');
},
function(first, last) {
console.log('Called with two arguments');
}
);
}

var users = new Users();
users.find();
users.find('Jack');
users.find('John', 'Resig');

关于Javascript函数重载,请解释John Resig(Jquery方式)文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28167484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com