Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to using Javascript prototypes without using the "new" keyword?

The fact that Javascript uses functions to create objects was confusing to me at first. An example like this is often used to highlight how prototypes work in Javascript:

function Car(){
  this.setModel=function(model){
    this.model=model;
  }
  this.getModel=function(){
    return this.model;
  }
}

function Bus(){}
Bus.prototype=new Car();

var obj=new Bus();
obj.setModel('A Bus');
alert(obj.getModel('A Bus');

Is it possible to use prototypes without using new FunctionName()? I.e. something like this:

var Car={
  setModel:function(model){
    this.model=model;
  },
  getModel:function(){
    return this.model
  }
}

var Bus={
  prototype:Car;
};

var obj=Bus;
obj.setModel('A Bus');
alert(obj.getModel());

This does not use functions and new to create objects. Rather, it creates objects directly.

Is this possible without deprecated features like Object.__proto__ or experimental functions like Object.setPrototypeOf()?

like image 291
Leo Jiang Avatar asked Dec 06 '25 12:12

Leo Jiang


1 Answers

Object.create gets you the behavior that you are looking for, but you have to call it instead of new:

// Using ES6 style methods here
// These translate directly to
// name: function name(params) { /* implementation here */ }
var Car = {
 setModel(model) {
    this.model = model;
  },
  getModel() {
    return this.model
  }
};

var Bus = Object.create(Car);

var obj = Object.create(Bus);
obj.setModel('A Bus');
alert(obj.getModel());

Alternatively, you can use the new ES 2015's __proto__ property to set the prototype at declaration time:

var Bus = {
  __proto__: Car
};

// You still need Object.create here since Bus is not a constructor
var obj = Object.create(Bus);
obj.setModel('A Bus');
alert(obj.getModel());

Some additional notes

You should add the methods to Car.prototype not inside of the constructor unless you need the private state (this way there is only one instance of the setModel method, rather than one instance of the method per instance of the class):

function Car() {}
Car.prototype.setModel = function(model) { this.model = model; };
Car.prototype.getModel = function(model) { return this.model; };

You can get around the new Car oddness with Object.create even with constructor functions:

function Bus {}
Bus.prototype = Object.create(Car);
like image 80
Sean Vieira Avatar answered Dec 08 '25 02:12

Sean Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!