1

If I add a property to Object.prototype like Object.prototype.sth = "something";

then, is there a way to hide the property for a specified object? I tried like this:

function Foo() {
// sth...
}
Foo.prototype = null;
var bar = new Foo();

however, bar still have access to the property sth;


bar.__proto__ = null or Foo.prototype.__proto__ = null works

3
  • 1
    Why ? What are you trying to do ? Commented May 22, 2013 at 7:43
  • 1
    It's not possible, but you can take a look at this answer: stackoverflow.com/a/2636719/2183827 Commented May 22, 2013 at 7:45
  • I'm just trying to understand the concept of prototype chain… Commented May 22, 2013 at 7:58

2 Answers 2

0

I think the way to do this is:

  function Foo() {
         this.sth = null
// or this.sth = undefined;
    }

    var bar = new Foo();
  • Foo.prototype = null;: the bar.__proto__ will point directly to Object.prototype.
  • Without Foo.prototype = null;: the bar.__proto__ will point to Foo.prototype, and Foo.prototype.__proto__ points to Object.prototype

Another way:

function Foo() {
// sth...
}
Foo.prototype.sth = undefined;
//or Foo.prototype.sth = null;
var bar = new Foo();
Sign up to request clarification or add additional context in comments.

4 Comments

It's just add a property to the object to preven Javascript to travel the prototype chain
@YOnder: i think it's one of the ways. You may use Foo.prototype.sth undefined;
Anyways, you have to override it by using its own properties or a nearer prototype properties.
Got it. I can assign the null value for the bar.__proto__
0

Actually, if you override Foo.prototype with null, the Foo's attributes will be deleted.

Foo.prototype.sth = 1;
bar = new Foo(); # Creates {sth:1}
Foo.prototype = null;
bar = new Foo(); # Creates {}

Take a look to the documentation page :

all objects inherit methods and properties from Object.prototype Object.prototype, although they may be overridden (except an Object with a null prototype, i.e. Object.create(null)).

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.