构造函数
function Preson(){this.name = name,this.age = age,}let temp = new Person()/*构造函数返回 对象 (返回this)如果手动加 return+基本数据类型则依然返回this如果是引用数据类型,则返回引用数据的地址 eg:[1,2,3] 或者 {}*/let temp = Person()//因为函数没有返回值,所以肯定是undefinedlog(typeof temp) //objectlog(typeof temp) //undefind 的类型 也是undefind
new 的四个步骤
- 创建了一个该类型的新的空对象{}
- 就像是:let obj = { }
- 将这个新对象的 proto 属性指向了类的 prototype
- _obj._pro = Cat.prototype
- 将构造函数内部的 this 指向了实例对象并执行构造函数中的代码
- this —> _obj // obj.name = name; log…(函数体内部数据)
- 返回新数组对象 _obj
- return 简单数据类型不影响返回值,复杂数据类型就返回该数据 // let xiaohua = obj
//构造函数//手动添加return//若return后是基本数据类型,则依然返回this//若return后是引用数据类型,则返回引用数据类型的地址function Person(name, age, money) {// 1this = {};// 2this = {// name: un,// age: un,// money: un// song:fn// __proto__:001 //赋值一个想像的引用地址// }this.name = name;this.age = age;this.money = money;this.song = function() { console.log(this.name); }// 4this.__proto__ = Person.prototype;//相当于将 Person.prototype 的引用地址给到 this.__proto__// 5this = p1;// 6return this;}let p1 = new Person('z3', 18, 100);console.log(p1);let p2 = new Person('l4', 18, 100);console.log(p1.__proto__.constructor == Person); // trueconsole.log(p1.__proto__.constructor === Object); // falseconsole.log(p1.__proto__.constructor.__proto__ === Function.prototype);console.log(p1.__proto__.constructor.__proto__.constructor === Function);
