在记录之前先问一个问题,r1 和 r2 分别打印什么?答案在最后
function MyFunction() {
this.name = "123";
return [4, 5, 6];
}
function MyFunction2() {
this.name = "123";
return "456";
}
const r1 = new MyFunction();
const r2 = new MyFunction2();
console.log(r1, r2);
举例:学生入学,创建学生信息。
1. 普通创建同学 - 每个同学结构一样,创建信息时重复劳动过多
const studentOne = { name: "同学1", age: 15 };
const studentTwo = { name: "同学2", age: 16 };
2. 构造器模式 - 可以省略重复结构,只需要个人的具体信息
function createObj(name, age) {
this.name = name;
this.age = age;
this.getInfo = function () {
console.log(`我叫${this.name},今年${this.age}岁`);
};
}
const ming = new createObj("小明", 18);
const mei = new createObj("小美", 19);
ming.getInfo();
mei.getInfo();
在学习 构造器 的时候突然发现一个 之前漏掉或忘记的知识点
问 r1 和 r2 分别打印什么?
function MyFunction() {
this.name = "123";
return [4, 5, 6];
}
function MyFunction2() {
this.name = "123";
return "456";
}
const r1 = new MyFunction();
const r2 = new MyFunction2();
console.log(r1, r2);
至于为什么 则需要研究一下 new 做了什么事情?
1. 创建一个空的简单 JavaScript 对象(即 {} );
2. 为步骤 1 新创建的对象添加属性 `__proto__` ,将该属性链接至构造函数的原型对象;
3. 将步骤 1 新创建的对象作为 `this` 的上下文;
4. 如果 `构造函数` 没有返回引用类型,则返回 `this`,否则返回 引用类型
function myNew(constructor) {
const obj = {};
Object.setPrototypeOf(obj, constructor.prototype);
const result = constructor.apply(obj, Array.prototype.slice.call(arguments, 1));
return result instanceof Object ? result : obj;
}