我已经使用jQuery很久了,所以在编写代码时,Vanilla JS我有点想知道我们如何才能使用类似的东西$。在香草JS中扩展。
基本上有这三种方法-
语法-Object.assign(target,... sources)
因此,您可以按照以下方式进行编码-
var obj = { a: 1,c:4 }, obj2 = {a:2,b:3};
var copy = Object.assign(obj, obj2);
console.log(copy); // { a: 1 }
Run Code Online (Sandbox Code Playgroud)
甚至可以进行深度克隆,请参考Mozilla Doc。
否则,如果要在代码中使用扩展。一个描述extends如下-取自这篇文章的香草JavaScript版本的jQuery.extend()
/* Pass in the objects to merge as arguments.
For a deep extend, set the first argument to `true`.*/
var extend = function () {
// Variables
var extended = {};
var deep = false;
var i = 0;
var length = arguments.length;
// Check if a deep merge
if ( Object.prototype.toString.call( arguments[0] ) === '[object Boolean]' ) {
deep = arguments[0];
i++;
}
// Merge the object into the extended object
var merge = function (obj) {
for ( var prop in obj ) {
if ( Object.prototype.hasOwnProperty.call( obj, prop ) ) {
// If deep merge and property is an object, merge properties
if ( deep && Object.prototype.toString.call(obj[prop]) === '[object Object]' ) {
extended[prop] = extend( true, extended[prop], obj[prop] );
} else {
extended[prop] = obj[prop];
}
}
}
};
// Loop through each object and conduct a merge
for ( ; i < length; i++ ) {
var obj = arguments[i];
merge(obj);
}
return extended;
};
Run Code Online (Sandbox Code Playgroud)通过代码中的此定义,extend()函数可用于扩展对象,如下所述-
var newObjectShallow = extend(object1, object2, object3);
Run Code Online (Sandbox Code Playgroud)
如果对象很简单(不需要深度克隆),则可以使用以下方法- 此处介绍了更多详细信息
var extend = function ( defaults, options ) {
var extended = {};
var prop;
for (prop in defaults) {
if (Object.prototype.hasOwnProperty.call(defaults, prop)) {
extended[prop] = defaults[prop];
}
}
for (prop in options) {
if (Object.prototype.hasOwnProperty.call(options, prop)) {
extended[prop] = options[prop];
}
}
return extended;
};
Run Code Online (Sandbox Code Playgroud)希望这可以帮助任何人在本机js中搜索$ .extend实现
| 归档时间: |
|
| 查看次数: |
2170 次 |
| 最近记录: |