将JavaScript对象合二为一 [英] Combining JavaScript Objects into One

查看:112
本文介绍了将JavaScript对象合二为一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Colorbox(jQuery插件)的函数,它接受了许多参数,如下所示:

I have a function called "Colorbox" (jQuery plugin) that takes a number of parameters like so:

$(this).colorbox({
    width : "500px",
    height : "500px"
});

我有几种不同类型的this,但每种都有自己的属性。像这样:

I have several different types of "this", though, each with their own properties. Like so:

var Type = {
  video: {
    width : "500px",
    height : "500px"
  },
  gallery: {
    width : "1065px",
    height : "600px"
  }
}

除此之外,我还有其他行为,逻辑和默认设置组(被覆盖通过更具体的)。我要做的是将所有适当的设置从多个对象推送到一个Object中,这样我就可以调用:

Beyond that, I have other behaviors, logic, and a 'default' group of settings (which get overwritten by more specific ones). What I'm trying to do is push all the appropriate settings, from multiple objects, into a single Object so I can just call:

$(this).colorbox(Settings);

我如何转移未知的属性组及其值(例如width和height )从Type.video到Settings?目标是能够调用Settings.height并获取我推入的值。

How would I transfer an unknown group of properties and their values (for example "width" and "height") from something like Type.video into Settings? The goal is to be able to call Settings.height and get back the value I pushed in.

推荐答案

看看JQuery 扩展方法。它可以合并两个对象及其所有属性。

Take a look at the JQuery extend method. It can merge two objects together and all their properties.

来自JQuery的示例页面:

From JQuery's example page:

var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);

现在设置包含合并的设置和选项对象。

Now settings contains the merged settings and options objects.

这篇关于将JavaScript对象合二为一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆