关于JavaScript的继承方式

107 阅读1分钟

本文已参与「 新人创作礼 」活动,一起开启掘金创作之路

关于如何进行图片优化 - 适合的才是最好的

本文是几年前总结的其中一篇,放在语雀一直没有对外公开。后续还有很多曾经的技术,可能会有一些陈旧,如果大家有感兴趣的,我也准备一些新的资料后续开放到掘金上。也算是有思考的输出。

1. 组合继承1

function Parent (name) {
 this.name = name;
 this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.getName = function () { return this.name; }
function Child (name, age) {
 Parent.call(this, name);  
 this.age = age;
}
Child.prototype = new Parent();

2. constructor class

class Base1 {
	constructor(eat , drink){
		this.eat = eat || "苹果";
		this.drink = drink || "可乐";
	}
	sleep(hour) {
		console.log (`我睡了${hour}小时`);
	}
}
class Base2 {
	constructor(b1 , b2) {
		this.b1 = b1;
		this.b2 = b2;
	}
	toString() {
		console.log (this.b1+"  "+this.b2);
	}
}
class Child1 extends Base1{
	constructor(eat , drink , sport) {
		super(eat,drink);
		this.sport = sport||"跑步";
	}
	toString() {
		return this.eat + "-"+ this.sport + "-" + this.drink
	}
}

let c = new Child1("火腿","汽水","爬山");

c.sleep(5);
console.log (c.toString());

3. 组合2 继承

function Person (name) {
	this.name = name;
}

Person.prototype.sayName = function (){
	return this.name;
}

function Child(name , age) {
	Person.call(this , "小明");	
	this.age = age;
}

let c = new Child();

console.log (c.name);

console.log (c.__proto__ === Child.prototype);

4. setPrototypeOf

function fn(name) {
	this.name = name;
}
fn.prototype.sayName = function () {
	return  this.name;
}

let obj = {}
Object.setPrototypeOf(obj,fn.prototype);

fn.call(obj , 'cc');

console.log (obj.name);
console.log (obj.sayName());

5. 组合集成 prototype

function Person (name) {
	this.name = name;
}
Person.prototype.sayName = function (){
	return this.name;
}
function Child(name , age) {
	this.age = age;
}
Child.prototype = new Person("ok");
let c = new Child();
console.log ( Child, c.name);

6. Object.create

var Parent = {
    getName: function() {
        return this.name;
    }
}
var child = Object.create(Parent, {
    name: { value: "www"},
    url : { value: "http://www.baidu.com"}
});
 
//Outputs: Object {name: "www", url: "http://www.baidu.com", getName: function}
console.log(child);
 
//Outputs: "www"
console.log(child.getName());