-
什么是构造函数
- 构造函数和工厂函数一样, 都时专门用于创建对象的
- 构造函数本质上是工厂函数的简写
-
构造函数和工厂函数的区别
构造函数的函数名称首字母必须大写
-
构造只能通过 new 来调用
function Person(myName, myAge) { // let obj = new Object(); // 系统自动添加的 // let this = obj; // 系统自动添加的 this.name = myName; this.age = myAge; this.say = function () { console.log("hello world"); } // return this; //系统自动添加的 } /* 1.当我们new Person("lnj", 34);系统做了什么事情 1.1会在构造函数中自动创建一个对象 1.2会自动将刚才创建的对象赋值给this 1.3会在构造函数的最后自动添加return this; */ let obj1 = new Person("lnj", 34); let obj2 = new Person("zs", 44); console.log(obj1); console.log(obj2);
-
构造函数性能问题
-
通过三个等号来判断两个函数的名称, 如果返回 true, 表示这个是同一个函数, 并且在同一块存储空间
function demo() { console.log("demo"); } // 通过三个等号来判断两个函数的名称, 表示判断两个函数是否都存储在同一块内存中 // 如果返回true, 表示这个是同一个函数 console.log(demo === demo);
-
判断两个对象对say方法是否在同一个存储空间中
function Person(myName, myAge) { // let obj = new Object(); // 系统自动添加的 // let this = obj; // 系统自动添加的 this.name = myName; this.age = myAge; this.say = function () { console.log("hello world"); } // return this; //系统自动添加的 } let obj1 = new Person("lnj", 34); let obj2 = new Person("zs", 44); // 由于两个对象中的say方法的实现都是一样的, 但是保存到了不同的存储空间中 // 所以有性能问题 console.log(obj1.say === obj2.say); // false
-
-
构造函数性能优化上
-
将say方法中的代码用函数封装
function mySay() { console.log("hello world"); } function Person(myName, myAge) { // let obj = new Object(); // 系统自动添加的 // let this = obj; // 系统自动添加的 this.name = myName; this.age = myAge; this.say = mySay; // return this; //系统自动添加的 } let obj1 = new Person("lnj", 34); let obj2 = new Person("zs", 44); console.log(obj1.say === obj2.say); // true
-
- 当前这种方式解决之后存在的弊端
1.1 阅读性降低了
1.2 污染了全局的命名空间
-
构造函数性能优化中
-
将say方法的代码用另一个方法封装
let fns = { mySay: function () { console.log("hello world"); } } function Person(myName, myAge) { // let obj = new Object(); // 系统自动添加的 // let this = obj; // 系统自动添加的 this.name = myName; this.age = myAge; this.say = fns.mySay; // return this; //系统之家添加的 } let obj1 = new Person("lnj", 34); let obj2 = new Person("zs", 44); console.log(obj1.say === obj2.say); // true
-
-
构造函数性能优化下
-
将say方法的代码当到prototype对象中, 这是专业的写法, 也是推荐的写法
function Person(myName, myAge) { // let obj = new Object(); // 系统自动添加的 // let this = obj; // 系统自动添加的 this.name = myName; this.age = myAge; // this.say = fns.mySay; // return this; //系统自动添加的 } Person.prototype = { say: function () { console.log("hello world"); } } let obj1 = new Person("lnj", 34); obj1.say(); let obj2 = new Person("zs", 44); obj2.say(); console.log(obj1.say === obj2.say); // true
-