在JavaScript中使用object literal实现继承

时间:2012-07-14 01:11:31

标签: javascript inheritance object-literal

我如何实现这一目标:

function Vehicle(){
    this.mobility = true;
};
function Car(){};
Car.prototype = new Vehicle();
var myCar = new Car();
console.log(myCar.mobility);

使用使用Object literals创建的对象?

我知道Object.create(),但有任何方式像

Car.prototype = new Vehicle();

实现这个目标?

3 个答案:

答案 0 :(得分:3)

以下是使用__proto__

进行操作的方法
var propertiesToInherit = { 'horsepower': 201, 'make': 'Acura' }
var myCar = {};
myCar.__proto__ = propertiesToInherit;

console.log(myCar.horsepower); // 201
console.log(myCar.make); // Acura

话虽如此,我会避免这样做。看起来好像是deprecated

答案 1 :(得分:1)

一种可能性是Prototype.js;除此之外,它允许您使用更清晰的语法创建和扩展JS类:

// 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!"

答案 2 :(得分:1)

我不知道我是否理解你的问题,但也许你可以试试这个:

var literal = { mobility: true };
function Car(){};
Car.prototype = literal;
var myCar = new Car();
console.log(myCar.mobility);

请注意,如果您更改文字,则会更改已创建的Car的所有实例。