Search code examples
javascriptprototypeprototypal-inheritance

Why can't I define properties or functions on prototype via Object.defineProperties()?


I want to set multiple properties on the prototype of my object at once, since Object.defineProperties() takes an object(and prototype is an object) and descriptors, and my object obj has already a prototype as it comes with every object,i am trying to modify the prototype of my object as follows

var obj = document.createElement(tn);

obj.prototype = Object.defineProperties(obj.prototype,{
    getName:{
        value:function(){
            alert("I have the tag"+this.tagName);
        },
        configurable:true
        }
    });

but I am getting an error:

Object.defineProperties called on non-object

why?


Solution

  • This is because, obj.prototype is undefined.

    You point it to some other object, properties will be added to it.

    JS has a prototype based inheritance model where an object inherits from another object, if it doesn't have a property or a method, it looks to its prototype object which is just another object with property and methods which again might have its own prototype object.

    You are getting the error Object.defineProperties called on non-object simply because obj.prototype is not an object and is undefined.

    set it to window or an empty {}, it should work for you.