没有“new”关键字的世界。
使用 Object.create() 并使用更简单的“散文式”语法。
*此示例针对 ES6 类和 TypeScript 进行了更新。
首先,Javascript 是 prototypal language,不是基于类的。它的真实性质以下面的原型形式表达,您可能会发现它非常简单,像散文,但功能强大。
TLDR;
Javascript
const Person = {
name: 'Anonymous', // person has a name
greet: function() { console.log(`Hi, I am ${this.name}.`) }
}
const jack = Object.create(Person) // jack is a person
jack.name = 'Jack' // and has a name 'Jack'
jack.greet() // outputs "Hi, I am Jack."
打字稿
在 TypeScript 中,您需要设置接口,这些接口将在您创建 Person 原型的后代时进行扩展。突变politeGreet 显示了在后代jack 上附加新方法的示例。
interface Person {
name: string
greet(): void
}
const Person = {
name: 'Anonymous',
greet() {
console.log(`Hi, I am ${this.name}.`)
}
}
interface jack extends Person {
politeGreet: (title: 'Sir' | 'Mdm') => void
}
const jack: jack = Object.create(Person)
jack.name = 'Jack'
jack.politeGreet = function(title) {
console.log(`Dear ${title}! I am ${this.name}.`)
}
jack.greet() // "Hi, I am Jack."
jack.politeGreet('Sir') // "Dear Sir, I am Jack."
这消除了有时令人费解的构造函数模式。 新对象继承自旧对象,但能够拥有自己的属性。如果我们尝试从新对象 (#greet()) 中获取新对象 jack 缺少的成员,则旧对象 Person 将提供该成员。
在Douglas Crockford's words: "Objects inherit from objects. What could be more object-oriented than that?"
您不需要构造函数,也不需要 new 实例化。您只需创建对象,然后扩展或变形它们。
此模式还提供immutability (partial or full) 和getters/setters。
干净整洁。它的简单性不会影响功能。继续阅读。
创建 Person prototype 的后代/副本(技术上比 class 更正确)。
*注意:以下示例是在 JS 中。要使用 Typescript 编写,只需按照上面的示例设置输入接口即可。
const Skywalker = Object.create(Person)
Skywalker.lastName = 'Skywalker'
Skywalker.firstName = ''
Skywalker.type = 'human'
Skywalker.greet = function() { console.log(`Hi, my name is ${this.firstName} ${this.lastName} and I am a ${this.type}.`
const anakin = Object.create(Skywalker)
anakin.firstName = 'Anakin'
anakin.birthYear = '442 BBY'
anakin.gender = 'male' // you can attach new properties.
anakin.greet() // 'Hi, my name is Anakin Skywalker and I am a human.'
Person.isPrototypeOf(Skywalker) // outputs true
Person.isPrototypeOf(anakin) // outputs true
Skywalker.isPrototypeOf(anakin) // outputs true
如果您觉得丢弃构造函数而不是直接赋值不太安全,一种常见的方法是附加 #create 方法:
Skywalker.create = function(firstName, gender, birthYear) {
let skywalker = Object.create(Skywalker)
Object.assign(skywalker, {
firstName,
birthYear,
gender,
lastName: 'Skywalker',
type: 'human'
})
return skywalker
}
const anakin = Skywalker.create('Anakin', 'male', '442 BBY')
将Person 原型分支到Robot
当你从Person原型分支Robot后代时,你不会影响Skywalker和anakin:
// create a `Robot` prototype by extending the `Person` prototype:
const Robot = Object.create(Person)
Robot.type = 'robot'
附加Robot独有的方法
Robot.machineGreet = function() {
/*some function to convert strings to binary */
}
// Mutating the `Robot` object doesn't affect `Person` prototype and its descendants
anakin.machineGreet() // error
Person.isPrototypeOf(Robot) // outputs true
Robot.isPrototypeOf(Skywalker) // outputs false
在 TypeScript 中,您还需要扩展 Person 接口:
interface Robot extends Person {
machineGreet(): void
}
const Robot: Robot = Object.create(Person)
Robot.machineGreet = function() { console.log(101010) }
而且你可以拥有 Mixins——因为……Darth Vader 是人类还是机器人?
const darthVader = Object.create(anakin)
// for brevity, property assignments are skipped because you get the point by now.
Object.assign(darthVader, Robot)
Darth Vader 获取Robot 的方法:
darthVader.greet() // inherited from `Person`, outputs "Hi, my name is Darth Vader..."
darthVader.machineGreet() // inherited from `Robot`, outputs 001010011010...
还有其他奇怪的事情:
console.log(darthVader.type) // outputs robot.
Robot.isPrototypeOf(darthVader) // returns false.
Person.isPrototypeOf(darthVader) // returns true.
优雅地反映了“现实生活”的主观性:
“他现在比人更像机器,扭曲而邪恶。” - 欧比旺克诺比
“我知道你很优秀。” - 卢克天行者
与 ES6 之前的“经典”等效项进行比较:
function Person (firstName, lastName, birthYear, type) {
this.firstName = firstName
this.lastName = lastName
this.birthYear = birthYear
this.type = type
}
// attaching methods
Person.prototype.name = function() { return firstName + ' ' + lastName }
Person.prototype.greet = function() { ... }
Person.prototype.age = function() { ... }
function Skywalker(firstName, birthYear) {
Person.apply(this, [firstName, 'Skywalker', birthYear, 'human'])
}
// confusing re-pointing...
Skywalker.prototype = Person.prototype
Skywalker.prototype.constructor = Skywalker
const anakin = new Skywalker('Anakin', '442 BBY')
// #isPrototypeOf won't work
Person.isPrototypeOf(anakin) // returns false
Skywalker.isPrototypeOf(anakin) // returns false
ES6 类
与使用对象相比更笨拙,但代码可读性还可以:
class Person {
constructor(firstName, lastName, birthYear, type) {
this.firstName = firstName
this.lastName = lastName
this.birthYear = birthYear
this.type = type
}
name() { return this.firstName + ' ' + this.lastName }
greet() { console.log('Hi, my name is ' + this.name() + ' and I am a ' + this.type + '.' ) }
}
class Skywalker extends Person {
constructor(firstName, birthYear) {
super(firstName, 'Skywalker', birthYear, 'human')
}
}
const anakin = new Skywalker('Anakin', '442 BBY')
// prototype chain inheritance checking is partially fixed.
Person.isPrototypeOf(anakin) // returns false!
Skywalker.isPrototypeOf(anakin) // returns true
进一步阅读
可写性、可配置性和免费的 Getter 和 Setter!
对于免费的 getter 和 setter,或额外的配置,您可以使用 Object.create() 的第二个参数,也就是 propertiesObject。它也可以在#Object.defineProperty 和#Object.defineProperties 中使用。
为了说明其用途,假设我们希望所有Robot 都严格由金属制成(通过writable: false),并标准化powerConsumption 值(通过getter 和setter)。
// Add interface for Typescript, omit for Javascript
interface Robot extends Person {
madeOf: 'metal'
powerConsumption: string
}
// add `: Robot` for TypeScript, omit for Javascript.
const Robot: Robot = Object.create(Person, {
// define your property attributes
madeOf: {
value: "metal",
writable: false, // defaults to false. this assignment is redundant, and for verbosity only.
configurable: false, // defaults to false. this assignment is redundant, and for verbosity only.
enumerable: true // defaults to false
},
// getters and setters
powerConsumption: {
get() { return this._powerConsumption },
set(value) {
if (value.indexOf('MWh')) return this._powerConsumption = value.replace('M', ',000k')
this._powerConsumption = value
throw new Error('Power consumption format not recognised.')
}
}
})
// add `: Robot` for TypeScript, omit for Javascript.
const newRobot: Robot = Object.create(Robot)
newRobot.powerConsumption = '5MWh'
console.log(newRobot.powerConsumption) // outputs 5,000kWh
并且Robot 的所有原型都不能是madeOf 别的东西:
const polymerRobot = Object.create(Robot)
polymerRobot.madeOf = 'polymer'
console.log(polymerRobot.madeOf) // outputs 'metal'