JavaScript:对比Class/构造函数 与 Object.create/new

787 阅读1分钟

继承

用构造函数继承

utils库中的inherits是实现了两个构造函数之间的继承。
util.inherits(ctr, SuperCtr)将superCtr的prototype作为ctr的prototype的原型

```JavaScript
var util = require('util');
function Person(f,l) {
	this.first = f;
	this.last = l;
}
Person.prototype.sleep = function() {
	console.log('I am sleeping');
}
function Police(f, l, n) {
	//Person.call(this, f, l);
	this.badge = n;
}
Police.prototype.greet = function() {
	console.log('Hello ' + this.first + ' ' + this.last + ' ' +this.badge);
}
util.inherits(Police, Person);

var officer = new Police('John', 'Doe', '1');

officer.greet();//Hello undefined undefined 1
officer.sleep();//I am sleeping
```

Police构造函数构造出的实例,可以获取Police中的公用方法和属性(greet)和私有属性(number),还有Person中的公用方法和属性(sleep)。但无法获取其私有属性
改造Police构造函数

function Police(f, l, n) {
	Person.call(this, f, l);
	this.badge = n;
}
//Hello John Doe 1
//I am sleeping

Police被执行了一次,并且通过call将其内部的this指向新构造的对象

用Class继承

class Person {
	constructor(f, l) {
		this.first = f;
		this.last = l;
	}
	sleep() {
		console.log('I am sleeping');
	}
}
class Police extends Person{
	constructor(f, l, n) {
		super(f, l);
		this.badge = n;
	}
	greet() {
		console.log('Hello ' + this.first + ' ' + this.last + ' ' +this.badge);
	}
}

var officer = new Police('John', 'Doe','1')

officer.greet();
officer.sleep();

私有属性写在constructor里(对应构造函数里);公用属性、方法写在类里(对应构造函数prototype);继承extends对应构造函数的utils.inheritssurper对应call

实例化

实例化除了可以用new,还可以用Object.create

var officer = new Police('John', 'Doe', '1');

等效

var officer = Object.create(Police.prototype,{
	first: {
		value: 'John',
	},
	last: {
		value: 'Doe',
	},
	badge: {
		value: '1',
	}
});
officer.greet();
officer.sleep();

相关内容:详解new