问题描述
jQuery扩展isPlainObject方法失败
问题出现的环境背景及自己尝试过哪些方法
想要自己是实现下jquery代码,写到extend方法的时候,需要实现深拷贝以及判断类型,我看源码是直接jQuery.extend( { isPlainObject: function( obj ) {} })
,但是我自己这么写的时候,就报错:jQuery.isPlainObject is not a function
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
(function (root) {
var jQuery = function () {
return new jQuery.prototype.init();
}
jQuery.fn = jQuery.prototype = {
init: function () {
},
css: function () {
}
}
// extend
jQuery.fn.extend = jQuery.extend = function () {
var target = arguments[0] || {};
var length = arguments.length;
var i = 1;
var deep = false;
var option, name, copy, src, copyIsArray, clone;
if (typeof target !== "boolean") {
deep = target;
target = arguments[1]
i = 2;
}
if (typeof target !== "object") {
target = {};
}
// 参数个数 1
if (length === i) {
target = this;
i--;
}
// 浅拷贝、深拷贝
for (; i < length; i++) {
if ((option = arguments[i]) != null) {
for (name in option) {
copy = option[name]
src = target[name]
// 报错:jQuery.isPlaninObject is not a function
console.log(jQuery.isPlainObject(copy))
if (deep && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
target[name] = jQuery.extend(deep, clone, copy);
} else if (copy != undefined) {
target[name] = copy;
}
}
}
}
return target;
}
// 共享原型
jQuery.fn.init.prototype = jQuery.fn
jQuery.extend({
// 类型检测
isPlainObject: function (obj) {
return toString.call(obj) === "[object object]"
},
isArray: function (obj) {
return toString.call(obj) === "[object Array]"
}
})
root.$ = root.jQuery = jQuery;
})(this);
页面引用
<script>
console.log($())
var ret = { name: "max", list: { age: "30" } };
var res = { list: { sex: "female" } }
var obj = $.extend(true, {}, ret, res);
console.log(obj)
</script>
你期待的结果是什么?实际看到的错误信息又是什么?
希望能调用isPlaninObject方法,判断类型,但是貌似扩展失败了,调用不到。
看你这句代码,
你都把jquery的原型指向改掉了