2

どうすればこれを達成できますか:

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();

それを達成するために?

4

3 に答える 3

4

使用方法は次の__proto__とおりです。

var propertiesToInherit = { 'horsepower': 201, 'make': 'Acura' }
var myCar = {};
myCar.__proto__ = propertiesToInherit;

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

そうは言っても、私はこれを避けたいと思います。非推奨のようです

于 2012-07-14T02:06:46.793 に答える
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!"
于 2012-07-14T01:45:15.677 に答える
1

私があなたの質問を正しく理解しているかどうかはわかりませんが、多分あなたはこれを試すことができます:

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

リテラルを変更すると、Car作成されたすべてのインスタンスが変更されることに注意してください。

于 2012-07-14T01:46:55.627 に答える