Dean
Dean

Reputation: 1084

Merge a function with an object with jQuery extend method, why's only function is returned?

I have the following code:

var object1 = function() {};
var object2 = {prop: "hello"};
$.extend(object1, object2)

In Chrome developer console, when type object1, only the function is returned. But I can type object1.prop. Why's that?

Upvotes: 0

Views: 57

Answers (2)

Joe. He
Joe. He

Reputation: 140

var object1 = function() {};
var object2 = {prop: "hello"};
merged = $.extend(object1, object2)
// function() {}
merged.prop
// "hello"

function with prop be returned;

Upvotes: 1

Leah Zorychta
Leah Zorychta

Reputation: 13409

The extend method from the jquery doc:

Description: Merge the contents of two or more objects together into the first object.

When you do this:

$.extend(object1, object2)

what you're saying is "take the properties of object2 (prop = "hello") and slap them onto object1. Therefore what you're doing is giving object1 a property called prop.

so another example:

// this object
var colours = { red: 1, green: 2, blue: 3 };

// will be merged into this one below
var people = { bob: 4, joe: 5 };

// like this!
$.extend(people, colours);

console.log(people);

// prints { red: 1, green: 2, blue: 3, bob: 4, joe: 5 }

Upvotes: 1

Related Questions