1.构造函数的基本类型
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
this.eat = function(){
console.log('吃操作');
}
}
var per1 = new Person('chen',24,'男');
2.模拟构造函数执行的伪代码
function Person (name, age) {
// 当使用 new 操作符调用 Person() 的时候,实际上这里会先创建一个对象
// var instance = {}
// 然后让内部的 this 指向 instance 对象
// this = instance
// 接下来所有针对 this 的操作实际上操作的就是 instance
this.name = name
this.age = age
this.sayName = function () {
console.log(this.name)
}
// 在函数的结尾处会将 this 返回,也就是 instance
// return this
}
3.构造函数和实例对象的关系
+ 可以识别对象的具体类型
+ 在每一个实例对象中的_proto_中同时有一个constructor属性,该属性指向创建该实例的构造函数
+ 对象的 constructor 属性最初是用来标识对象类型的,
+ 但是,如果要检测对象的类型,还是使用 instanceof 操作符更可靠一些
+ 总结
* 构造函数是根据具体的事物抽象出来的抽象模板
* 实例对象是根据抽象的构造函数模板得到的具体实例对象
* 每一个实例对象都具有一个 constructor 属性,指向创建该实例的构造函数(说法不严谨)
* 可以通过实例的 constructor 属性判断实例和构造函数之间的关系(不严谨,建议使用instanceof操作符)
4.构造函数的问题
构造函数本身存在浪费内存的问题
优化:可以把需要共享的函数定义到构造函数外部;多个函数放到一个对象中用来避免全局命名空间冲突的问题