Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

jquery - Combining JavaScript Objects into One

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

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

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"
  }
}

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);

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...