答案:
function Person(name) {
this.name = name;
}
var person = new Person("qilei");
// new一个对象的四个过程:
// 1. 创建空对象;
var obj = {};
// 2. 设置原型链: 设置新对象的 constructor 属性为构造函数的名称,设置新对象的__proto__属性指向构造函数的 prototype 对象;
obj.constructor = Person;
obj.__proto__ = Person.prototype;
// 3. 改变this指向:使用新对象调用函数,函数中的 this 指向新实例对象obj:
var result = Person.call(obj); //{}.构造函数();
// 4. 返回值:如果无返回值或者返回一个非对象值,则将新对象返回;如果返回值是一个新对象的话那么直接返回该对象。
if (typeof(result) == "object") {
person = result;
} else {
person = obj;
}
[参与互动](https://github.com/yisainan/web-interview/issues/187)
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有