功能代码集合

JS原型链

1
2
3
4
5
6
7
8
9
10
11
function Person() {}
Person.prototype.name = "abc";
Person.prototype.sayName = function () {
console.log(this.name);
};

let person = new Person();

person.__proto__ = Person.prototype;
String.__proto__ = Function.prototype;
String.constructor = Function;

JS继承

原型继承

1
2
3
4
5
6
7
8
9
10
function Parent() {
this.name = "Parent";
this.sex = "male";
}

function Child() {
this.name = "Child";
}

Child.prototype = new Parent();

构造函数继承

1
2
3
4
5
6
7
function Parent(name) {
this.name = name;
}

function Child() {
Parent.call(this, "Child");
}

组合继承

1
2
3
4
5
6
7
8
9
10
function Person(name) {
this.name = name;
}

function Child(name) {
Person.call(this, name);
}

Child.prototype = new Persion();
Child.prototype.constructor = Child;

new关键字

1
2
3
4
5
6
function _new(constructor, ...arg) {
let obj = {};
obj.__proto__ = constructor.prototype;
let res = constructor.apply(obj, arg);
return Object.prototype.toString.call(res) === "[object Object]" ? res : obj;
}