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.

hemkaran_raghav
  • 1,346
  • 11
  • 25

2 Answers2

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"
maček
  • 76,434
  • 37
  • 167
  • 198
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);
Andre
  • 2,449
  • 25
  • 24