简体   繁体   English

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

[英]Achieve inheritance using object literal in JavaScript

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 我知道Object.create()但有什么办法

Car.prototype = new Vehicle();

to achieve that ? 实现这一目标?

Here's how you do it using __proto__ : 使用__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 ; 一种可能是Prototype.js ; among other things, it allows you to create and extend JS classes using a cleaner syntax: 除其他外,它允许您使用更简洁的语法创建和扩展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!"

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. 请注意,如果更改文字,则将更改创建的Car所有实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM