簡體   English   中英

使用JavaScript中的對象文字實現繼承

[英]Achieve inheritance using object literal in JavaScript

我如何做到這一點:

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

使用使用對象文字創建的對象?

我知道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所有實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM