在JavaScript中使用对象文字实现继承

Achieve inheritance using object literal in JavaScript

本文关键字:文字 实现 继承 对象 JavaScript      更新时间:2023-09-26

如何实现这一点:

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

使用用Object文字创建的对象?

我知道Object.create(),但有没有类似的方法

Car.prototype = new Vehicle();

实现这一目标?

以下是如何使用__proto__:

var propertiesToInherit = { 'horsepower': 201, 'make': 'Acura' }
var myCar = {};
myCar.__proto__ = propertiesToInherit;
console.log(myCar.horsepower); // 201
console.log(myCar.make); // Acura

话虽如此,我会避免这样做。看起来它已被弃用

一种可能性是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!"

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

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

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