一、 构造函数一般以大写字母开头(大写小都可以,规范是大写开头)
function Fruits(type= "apple", color= "red") {
this.type= type;
this.color= color;
}
二、构造函数会执行以下几个过程:
(1)使用new关键字调用时,会创建一个新的内存空间
(2)函数体内部的this指向该内存
(3)执行函数体内的代码:给this添加属性,就相当于给实例添加属性
(4)默认返回this
var p1 = new Fruits('apple', 'red');
// 这种情况每new一个对象,就回创建一个新的内存空间
p1.type= 'banana'
console.log(new Fruits()) //{ type: 'apple', color: 'red' }
console.log(p1) //{ type: 'banana', color: 'red' }
三、深究构造函数的返回值:
1、默认返回this
2、手动添加返回值:
1) 如果是基本数据类型,最终还是返回this
2)如果是复杂的数据类型(对象),最终返回该对象
2、(1)
function Fruits1() {
this.name = 'lan';
return 50;
}
var f1 = new Fruits1();
var f1_1 = Fruits1()
//以上例子是普通函数调用,则返回50;
console.log(f1) //{name:'lan'}
console.log(f1_1 ) //50
2、(2)
function Fruits2() {
this.type= 'banana';
return ['a', 'b', 'c', 'd'];
}
var f2 = new Fruits2();
console.log(f2) //[ 'a', 'b', 'c', 'd' ]
console.log(f2.type); //undefined
console.log(f2.length); //4
console.log(f2[0]); //a
四、用new 和不用new 调用构造函数有什么不同?
1、用new调用
1)创建一个this变量,该变量指向一个空对象,并且该对象继承函数的原型
2)属性和方法会被加入this引入的对象中;
3)若没有显性(指定)返回其它对象,则隐形(默认)返回this对象。
用伪程序来展示以上过程:
function Fruits(type) {
//创建this变量,指向空对象
var this = {};
this.type = type;
this.say = function () {
return "This is" + type;
}
//返回this对象
return this;
}
2、直接调用构造函数
this指向window,除了指定返回值,否则不会默认返回任何对象;
例子:
var f = Fruits('apple');
f(); //undefined
window.name; //apple
// 显然这不是我们想要的结果
总结:
为了防止忘记使用new关键字而带哦用构造函数,可以加一些判断条件强行调用new
function Fruits(type) {
if (!(this instanceof Fruits)) {
return new Fruits(type);
}
this.type = type;
...
}