0

I'm trying to better understand object relationships in Javascript. I have the following object:

var product = {id: 1, name: 'Test Product', sku: {id: 2, sku: 'ABC'}};

Now, I also set the following variable:

var appSku = product.sku;

If product.sku changes to a new object, will appSku update? Meaning, if somewhere else in the code I do this:

product.sku = {id: 3, sku: 'EFG'};

How can I ensure that the appSku variable gets the new value of product.sku?

1
  • Yes I tried it out in js console and know it doesn't work. Commented Oct 3, 2014 at 19:19

1 Answer 1

4

If product.sku changes to a new object, will appSku update?

No

How can I ensure that the appSku variable gets the new value of product.sku?

You would have to write it as a function accesses sku via a reference to the Object product, e.g.

var appSku = (function (o) {
    return function () {
        return o.sku;
    }
}(product));

And always use appSku()

This isn't really helpful in your case, though as using product.sku directly is much cleaner


This said, if product.sku is not changed to a new Object, but rather the previous one just has it's properties modified then appSku and product.sku would still be the same thing

Sign up to request clarification or add additional context in comments.

1 Comment

Does it need to be written as you show it with a closer around it? What is the reason for that? Can't it just be a single function that returns the value of product.sku?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.