2012-07-14 29 views

回答

2

这是它使用__proto__你怎么做:

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

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

话虽这么说,我会避免这样做。它看起来像是deprecated

+0

嗯,你是我想到的。但不幸的是,它已被废弃,如你所说。 – 2012-07-14 02:11:15

+0

是否有你不想使用Object.create的原因?还是标准的功能继承? – jalbee 2012-07-14 02:15:47

+0

不,但我已经在某处读过'Object.create()'是一个ECMAScript5特性,所以我很担心跨浏览器的兼容性。我想知道它的替代方案,以防万一我不得不使用对象文字而不是构造函数。 – 2012-07-14 02:20:31

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

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

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

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

+0

雅,但是可以在没有制作Car构造函数的情况下实现。我的意思是直接来自'myCar'对象。 – 2012-07-14 01:58:06

+1

你的意思是'var myCar = literal;'?或者,也许你想将文字的内容复制到汽车中? – 2012-07-14 02:00:08

+0

我的意思是我们可以直接从'literal'继承'myCar',或者以某种方式创建'Car'构造函数,然后'Car.prototype = literal'并从中实例化'myCar'?我的意思是我们可以使用object literal创建'myCar',然后从object'literal'继承它吗? – 2012-07-14 02:09:34

相关问题