构造函数实质就是工厂函数的简写
注意点:
1.构造函数的函数名称首字母必须大写 2.构造函数只能通过new来调用
当我们new了一个对象后会做出以下事情: 1.会在构造函数中自动创建了一个对象 2.会自动将刚才创建的对象赋值给this 3.会在构造函数的最后自动添加return this
<script> function Person(name, age) { // let obj = new Object() 系统自动添加 // let this = obj 系统自动添加 this.name = name; this.age = age; this.say = function() { console.log("Hello World"); } // return this 系统自动添加 } let obj1 = new Person("zs", 20); let obj2 = new Person("ls", 25); console.log(obj1); console.log(obj2); </script>控制台输出:
问:obj1 和 obj2 调用的方法来自同一地址吗??
console.log(obj1.say === obj2.say);控制台输出:
当new了一个对象后,系统自动开辟了一个存储空间,里面有分为很多内存来存放对象的属性和方法obj1和obj2开辟了两个不同的存储空间,所以两者的地址不同。
如何进行优化呢?? 关键词:prototype
<script> function Person(name, age) { // let obj = new Object() 系统自动添加 // let this = obj 系统自动添加 this.name = name; this.age = age; // return this 系统自动添加 } Person.prototype = { say: function() { console.log("Hello World"); } } let obj1 = new Person("zs", 20); let obj2 = new Person("ls", 25); console.log(obj1); console.log(obj2); obj1.say(); obj2.say(); console.log(obj1.say === obj2.say); </script>prototype特点
1.存储在prototype中的方法可以被对应构造函数创建出来的所有对象共享 2.prototype中除了可以存储方法以外,还可以存储属性
<script> function Person(name, age) { this.name = name; this.age = age; } Person.prototype = { type: '人', say: function() { console.log("Hello World"); } } let obj1 = new Person("zs", 20); let obj2 = new Person("ls", 25); console.log(obj1); console.log(obj2); obj1.say(); console.log(obj1.type); obj2.say(); console.log(obj2.type); </script>控制台输出: 3.prototype如果出现了和构造函数中同名的属性或者方法,对象在访问的时候,访问到的是构造函中的数据
<script> function Person(name, age) { this.name = name; this.age = age; this.type = '构造函数中的人'; this.say = function() { console.log("构造函数中的Hello World"); } } Person.prototype = { type: '人', say: function() { console.log("Hello World"); } } let obj1 = new Person("zs", 20); let obj2 = new Person("ls", 25); console.log(obj1); console.log(obj2); obj1.say(); console.log(obj1.type); obj2.say(); console.log(obj2.type); </script>控制台输出:
prototype应用场景 prototype中一般情况下用于存储所有对象都相同的一些属性以及方法 如果是对象特有的属性或者方法,我们会存储到构造函数中