gpt4 book ai didi

javascript - 纯 JavaScript 每个函数都不起作用

转载 作者:行者123 更新时间:2023-11-30 12:49:17 25 4
gpt4 key购买 nike

在纯 JavaScript 中,我试图创建 jQuery.each 函数。到目前为止,我只是从查询源代码中复制了部分内容。

这是我目前所拥有的:

var class2type = {
"[object Boolean]": "boolean",
"[object Number]": "number",
"[object String]": "string",
"[object Function]": "function",
"[object Array]": "array",
"[object Date]": "date",
"[object RegExp]": "regexp",
"[object Object]": "object",
"[object Error]": "error"
},
core_toString = class2type.toString;
function type(obj) {
if (obj == null) {
return String(obj);
}
return typeof obj === "object" || typeof obj === "function" ? class2type[core_toString.call(obj)] || "object" : typeof obj;
}
function isWindow(obj) {
return obj != null && obj == obj.window;
}
function isArraylike(obj) {
var length = obj.length,
type = type(obj);

if (isWindow(obj)) {
return false;
}

if (obj.nodeType === 1 && length) {
return true;
}

return type === "array" || type !== "function" && (length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj);
}

function each( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );

if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );

if ( value === false ) {
break;
}
}
}
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );

if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );

if ( value === false ) {
break;
}
}
}
}
return obj;
}

它应该可以正常工作,但是当我尝试运行以下代码时:

each([1, 2], function( index, value ) {
alert( index + ": " + value );
});

我收到以下错误:TypeError: 'undefined' is not a function (evaluating 'type(obj)') 这里指的是:

23| function isArraylike(obj) {
24| var length = obj.length,
25| type = type(obj);

为什么这段代码不起作用?我只是直接使用了 jQuery 源代码中的部分。

谢谢。

最佳答案

问题是变量提升和阴影之一。您在当前范围之外有一个 type 函数,并且您希望在第 25 行的语句中将它用作函数,然后将结果传递给具有相同名称的局部变量:

function type () {};

function isArraylike(){
var type = type(1);
};

实际上,由于变量提升,代码看起来是这样的:

function type() {};

function isArraylike(){
var type; // type is undefined here
type = type(1);
};

因此您可以看到,在整个isArraylike 函数中,type 始终是一个变量,并且永远不会从外部作用域引用该函数。解决方法很简单:为函数或变量使用另一个名称。

关于javascript - 纯 JavaScript 每个函数都不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21518990/

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