JS 手写 new
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function Person(name, age) {
this.name = name;
this.age = age;
return 1;
}
Person.prototype.study = function () {
console.log("HTML5");
}
var p1 = new Person("xiaowang", 30);
console.log(p1)
function myNew(constr) {
var obj = {};
var re = constr.apply(obj, Array.from(arguments).slice(1));
obj.__proto__ = constr.prototype;
if (typeof re === 'object' && re != null || typeof re === "function") {
return re;
}
return obj;
}
var p1 = myNew(Person, "xiaowang", 30);
var p2 = myNew(Person, "xiaoli", 20);
console.log(p1, p2);
console.log(p1.constructor)
console.log(p1.study === p2.study)
</script>
</body>
</html>