0

I am new to JS, I write below code, but I got the error "Prototype is not defined".

var proto = {
    describe: function () {
        return 'name: ' + this.name;
    }
};

var obj = {                
    [[Prototype]]: proto, //error in this line
    name:'obj'
};

console.log(proto.describe());
console.log(obj.describe());
1
  • [[prototype]] is an internal property, not a valid name for a key. You want to use Object.create Commented Sep 6, 2016 at 12:57

1 Answer 1

2

[[Prototype]] is only specification-speech for an internal property (the link in the prototype chain). To link obj to proto through the prototype chain, you can use Object.create:

   var obj = Object.create(proto);
   obj.name = 'obj';

Or Object.setPrototypeOf in ES6/ES2015:

    var obj = {                
        name:'obj'
    };

    Object.setPrototypeOf(obj, proto);

Alternatively, there is the legacy property __proto__, which is not necessarily recommended though:

    var obj = {                
        __proto__: proto,
        name:'obj'
    };
Sign up to request clarification or add additional context in comments.

3 Comments

Don't use __proto__. It's been officially deprecated with ES6. Use Object.setPrototypeOf instead if you have to.
Oh, I wasn't aware of that, Allen Wirfs-Brock even "recommended" using it: twitter.com/awbjs/status/730789464021159938. Object.setPrototypeOfmodifies the prototype of a live object, so there will be a performance hit. __proto__ in the object literal should have avoided that. Looks like there is no clean method to link object literals anymore…
If Object.setPrototypeOf is used immediately after the object creation, it shouldn't have a performance hit.

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.