0

I want stop inheriting a certain property from the parent object. How can I achieve that through inheritance in Javascript?

Here's an example:

var fun1 = function () {
    this.name = "xxx";
    this.privatenumber = 98765432100;
}
fun1.prototype.f = "yyy";
var obj1 = new fun1();
var fun2 = function () {}
fun2.prototype = Object.create(obj1);
var obj2 = new fun2();

In this example I don't want to inherit the privatenumber property to child.

2
  • You should edit this to make the formatting easier to read. Commented Aug 13, 2015 at 2:43
  • you can make that property as private Commented Aug 13, 2015 at 3:07

2 Answers 2

1

Don't use instances in the prototype chain, inherit directly from the prototype.

If the instance with the inheritance should be constructed by the other constructor too, tell it so

function Fun1() {
    this.name = "xxx";
    this.privatenumber = 98765432100;
}
Fun1.prototype.f = "yyy";

function Fun2() {
    // if instances of Fun2 should be constructed by Fun1 then
    Fun1.call(this);
    // and if you still don't want `privatenumber` which is now an own property, delete it
    delete this.privatenumber;
}
Fun2.prototype = Object.create(Fun1.prototype);

Now look at what we have;

var foo = new Fun2(); // Fun2 own `{name: "xxx"}`, inherting `{f: "yyy"}`
'privatenumber' in foo; // false
Sign up to request clarification or add additional context in comments.

Comments

0

A simple way is overriding it with undefined:

fun2.prototype = Object.create(obj1);
fun2.prototype.privatenumber = undefined;
var obj2 = new fun2();
obj2.privatenumber; // undefined

Note that "privatenumber" in obj2 will still return true.

1 Comment

Notice that .privatenumber is not a prototype, but rather an instance property. Of course, the class isn't setup properly either.

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.