js中构造函数的理解
https://blog.youkuaiyun.com/sinat_21742529/article/details/83659459
一、构造函数的运行机制
(1) 当以 new 关键字调用时,会创建一个新的内存空间,标记为 Animal 的实例。
(2)函数体内部的 this 指向该内存
(3) 执行函数体内的代码
通过上面的讲解,你就可以知道,给 this 添加属性,就相当于给实例添加属性。
(4) 默认返回 this
this指向问题看https://www.cnblogs.com/pssp/p/5216085.html
由于函数体内部的this指向新创建的内存空间,默认返回 this ,就相当于默认返回了该内存空间,也就是上图中的 #f1。此时,#f1的内存空间被变量p1所接受。也就是说 p1 这个变量,保存的内存地址就是 #f1,同时被标记为 Person 的实例。
eg:
function Person(name, gender, hobby) {
this.name = name;
this.gender = gender;
this.hobby = hobby;
this.age = 6;
}
var p1 = new Person('zs', '男', 'basketball');
p1{
name:'zs',
gender :'男',
hobby:'basketball',
age:6
}
二、构造函数的返回值
1.没有返回值(return),默认返回this
2.返回的是一个基本类型或者null的话,还是返回this,否则返回return值
***eg**:function Person(name){
this.name = name;
this.say = function(){
return "I am " + this.name;
}
var that = {};
that.name = "It is that!";
return that;
}
var person1 = new Person('nicole');
person1.name; // "It is that!"*