How do i achieve this :
function Vehicle(){
this.mobility = true;
};
function Car(){};
Car.prototype = new Vehicle();
var myCar = new Car();
console.log(myCar.mobility);
Using objects created with Object literals ?
I know about Object.create() but is there any way like
Car.prototype = new Vehicle();
to achieve that ?
Here's how you do it using __proto__
:
var propertiesToInherit = { 'horsepower': 201, 'make': 'Acura' }
var myCar = {};
myCar.__proto__ = propertiesToInherit;
console.log(myCar.horsepower); // 201
console.log(myCar.make); // Acura
That being said, I would avoid doing this. It looks like it is deprecated
One possibility would be Prototype.js ; among other things, it allows you to create and extend JS classes using a cleaner syntax:
// properties are directly passed to `create` method
var Person = Class.create({
initialize: function(name) {
this.name = name;
},
say: function(message) {
return this.name + ': ' + message;
}
});
// when subclassing, specify the class you want to inherit from
var Pirate = Class.create(Person, {
// redefine the speak method
say: function($super, message) {
return $super(message) + ', yarr!';
}
});
var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"
I don't know if I understand your question correctly, but maybe you could try this:
var literal = { mobility: true };
function Car(){};
Car.prototype = literal;
var myCar = new Car();
console.log(myCar.mobility);
Note that if you change the literal, you change all instances of Car
that were created.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.