Search code examples
javascriptfunctioninheritanceconstructorprototype

Is it possible to access the prototype object of function by its function itself


for example

//creating constructor function

function Something(){}

//adding name property to Something prototype


Something.prototype.name='javascript';

is it possible to access name property from its object itself?

//like

Something.name

// but here output will be 'undefined'

// code

function Fan(){}

Fan.prototype.speed='high';

Fan.speed

//output of (Fan.speed) undefined

Solution

  • You can create an instance of the object and then access it:

    function Something() {}
    Something.prototype.name = 'javascript';
    // create an instance for that
    var x = new Something();
    console.log(x.name);
    
    //Another set of examples, note the prototype on the objects function has no instance so the getName.protytppe.bucket
    const another = {
      secret: "skim",
      name: "cream",
      getName: function() {
        return this.name;
      },
      getSecret: function() {
        return this.secret;
      },
      makeButter: function(n) {
        this.name = n;
        return `We made {this.name} from cream`;
      }
    };
    another.getName.prototype.bucket = "lot-o-milk"
    
    var n = Object.create(another);
    console.log(n.name);
    console.log(n.getName());
    // make cream into butter
    n.name = "butter";
    console.log(n.name);
    console.log(n.getName());
    // turn butter back to cream
    delete n.name;
    console.log(n.name);
    console.log(n.getName());
    n.makeButter('yellow');
    console.log(n.getName());
    console.log(n.getSecret(), n.getName.prototype.bucket);