原生JS手写new方法

版权声明:本文为博主前端基础文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function Parent() {
this.name = "parent";
this.say = function() {
console.log("say")
}
}

Parent.prototype = {
walk: function() {
console.log("walk")
}
}

function newfn(fn) {
if (typeof fn !== 'function') return;
let son = {};
fn.call(son);
fn.prototype.constructor = fn;
son.__proto__ = fn.prototype;
return son;
}
let son1 = newfn(Parent);
son1.walk();