0

I'm in the process of converting a classical OOP project to JS. Everything goes well and I just need to know if one of the methods I used has a shorthand/conventional way to achieve the same I did with it.

In my design I needs to create an empty object with a specific prototype. I used an empty dummy function as the constructorsince I needed an empty object. I can't use new Object() since I need to attach a prototype before the creation.

Here is my code:

var baseObj = {name: '', id: 0}

function emptyObj () {
    //this is really a dummy
}

emptyObj.prototype = Object.create(baseObj);

myUser = new emptyObj();

Please note that I have to follow this pattern and my project works very well with it. I just want to know if there is a shorthand/conventional method to create an empty object with a prototype.

Please stick to ES5.

2
  • Shorthand to those 2 lines of code? Wrap them in a function and it will be one line of code. Commented Dec 11, 2015 at 5:54
  • if (i==2) { foo = true}; can be foo = i ==2; A short hand method for 2 lines of code. It's not about the number of lines. It is about the concept and the quality of your code. Commented Dec 11, 2015 at 5:56

1 Answer 1

1

I just want to know if there is a shorthand/conventional method to create an empty object with a prototype

Yes, there is one that does exactly this. And you've already used it. It's called Object.create.

Your code is exactly equivalent to

var baseObj = {name: '', id: 0};
myUser = Object.create(Object.create(baseObj));

I'm not sure though whether you really intended this two-level inheritance or whether a single invocation would be enough.

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

1 Comment

Exactly! I should have thought of that. Thanks.

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.