最近两天,我试图了解我的代码中的一个问题。
代码在这里: http://jsfiddle.net/a7wkpngr/
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
$.ajax({
url: '/',
data: $.extend({}, "")
})
如果你尝试运行这段代码,你会看到
TypeError: undefined is not a function // of course, coz this === window
我试图找到“为什么”。我发现:
- 问题出在
$.extend
中(如果第二个参数是对象,则没有异常(exception))。 - 如果你在没有
$.ajax
的情况下运行$.extend
,一切正常 - Jquery 源代码中没有关于大写的内容。
所以,问题是 - String.capitalize()
如何以及为何运行。
附言我知道,我知道,扩展原生类非常糟糕。
最佳答案
调试代码可以看到,在使用extend with empty选项时,会跳到jquery源码(2.0.1版本)的201行。
如果你在这里放置断点,当调用 ajax extend 时。参数长度为2,一个为{},另一个为""。
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
在属性上循环 for ( name in options ),遍历 String 的属性,所以实际上它应该添加所有字符串属性,但它只是添加你添加的大写函数并将其返回给 ajax 参数。第一个 for 循环只执行一次,因为如果长度为 2 并且内部 for 只运行一次,即在 capitalize 方法上。
现在检查以下输出:
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
String.prototype.capitalize2 = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
String.prototype.trim = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
Object.defineProperty(String.prototype, 'test',
{
value: function(){ return "test" },
enumerable: false
});
Object.defineProperty(String.prototype, 'test2',
{
value: function(){ return "test" },
enumerable: true
});
for (var key in "") {
console.log(key);
}
控制台输出:
大写
大写2
测试2
这导致您只能迭代可枚举的属性。
在这里检查 jsfiddle:http://jsfiddle.net/w9kdp96a/1/
来自 mozilla:
The for..in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
因此,如果您将 capitalize 方法定义为
Object.defineProperty(String.prototype, 'capitalize',
{
value: function(){ return this.charAt(0).toUpperCase() + this.slice(1); },
enumerable: false
});
它不会在 ajax 数据中。
关于javascript - 扩展 JavaScript String 和 JQuery.ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25404505/