0

I am new to Javascript. I have defined an object using object initializer method.

var obj = { a : "A";
            b : "B";
            myFunc = function() {
                alert("Hello"):
            }

Now I want to create another object that will be child of Obj. How can I do that.

var obj1 = new obj();

is not working.

2
  • var obj1 = Object.create(obj); Commented Dec 3, 2013 at 6:31
  • Maybe this answer will help: stackoverflow.com/a/16063711/1641941 Commented Dec 3, 2013 at 6:43

2 Answers 2

2

First off, you have a syntax error with

myFunc = function() { ...

Anyway, this is how you'll want to set it up

function Foo() {
  this.a = "A";
  this.b = "B";
}

Foo.prototype.myFunc = function() {
  alert("hello");
};

Now to create your child object

function Bar() {
  Foo.call(this); // call parent constructor; optional
}

// setup child prototype
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;

Check it out

var b = new Bar();

b instanceof Bar; // true
b instanceof Foo; // true

b.constructor.name; // Bar

b.myFunc; // "hello"
Sign up to request clarification or add additional context in comments.

Comments

1

To do it the way you wanted to:

var obj = {
    a: "A",
    b: "B",
    myFunc: function () {
        alert("Hello");
    }
};

var obj1 = Object.create(obj)
obj1.a = 2;
console.log(obj1);
console.log(obj);

Comments

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.