没有“new”关键字的世界。
使用 Object.create() 更简单的“散文式”语法。
*此示例针对 ES6 类和 TypeScript 进行了更新。
首先,Javascript 是一种原型语言,而不是基于类的。它的真实性质以下面的原型形式表达,您可能会看到它非常简单,像散文一样,但功能强大。
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
在 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 的话来说:“对象继承自对象。还有什么比这更面向对象的呢?”
您不需要构造函数,也不需要new
实例化。您只需创建对象,然后扩展或变形它们。
此模式还提供不变性(部分或全部)和getter/setter。
整洁明了。它的简单性不会影响功能。继续阅读。
创建 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
当您Robot
从Person
原型分支后代时,您不会影响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——因为……达斯维达是人还是机器人?
const darthVader = Object.create(anakin)
// for brevity, property assignments are skipped because you get the point by now.
Object.assign(darthVader, Robot)
达斯维达获得以下方法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'