0

I'm new to Prototypal inheritance and I've been stuck in an easy task

I have something like this:

var test1 = {
       clear : function () { 
         alert('hey');
       } 

 }

 var test2 = {
       varB : 2

 }

I would like to test2 extend from test1. Can anyone give me a direction? Should I still use Object.create, or maybe a function + call method? Im a bit confused here.

Every example that i found are based on extending and then setting attributes, methods, etc.. But my object is already declared here.

Thanks!

1

3 Answers 3

1

In modern browsers, you can use Object.setPrototypeOf:

Object.setPrototypeOf(test2, test1);

There is currently no other (official) way to change the prototype of an existing object.

If you are just creating a simple object, you can use Object.create:

var test2 = Object.create(test1);
test2.varB = 2; // or Object.assign(test2, {varB: 2});

If you don't actually need inheritance, merging the objects with Object.assign would be an option:

Object.assign(test2, test1);

This simply copies the properties from test1 to test2. Unlike with inheritance, changes to test1 don't impact test2.


For more information, I suggest to have a look at

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

Comments

0

Your can use prototype to do inheritance. But it just one of some inherit ways in javascript.

function test1() {}
test1.prototype.clear = function () {
    alert('hey');
}

function test2() {}
test2.prototype = new test1();
test2.prototype.varB = 2;

var test2Instance = new test2();

And search more javasrcipt inheritance methods with google by yourself.

Comments

0

A very basic approach would be

test2.__proto__ = Object.create(test1)

So you will have clear function available in test2 object.

1 Comment

MDN Object.prototype.__proto__ :[...]The __proto__ property is deprecated and should not be used.[...]

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.