构造函数
function fn(name, birthday) {
this.name = name;
this.birthday = birthday;
this.life = 1;
this.money = 0;
this.makeMoney = function () {
this.money += 1;
}
};
var obj = new fn("karen", "1997-02-03");
console.log(obj);
obj.makeMoney();
new fn(); new关键字后面跟函数 是一个表达式(运算符) 创建对象的运算 整个表达式一定会得到一个对象:
1. 创建一个空对象
2. 运行构造函数 让内部的this指向创建的对象(让创建的空对象去调用构造函数)
3. 整个表达式的结果看函数的返回值
3.1 返回值是引用数据 那么就是返回值
3.2 返回值不是引用数据 那么就是这个运行完毕之后的创建的那个对象
function fn(name, birthday) {
this.name = name;
this.birthday = birthday;
this.life = 1;
this.money = 0;
this.makeMoney = function () {
this.money += 1;
}
};
var re = new fn("jack", "2001-02-03");
// 1. {}
// 2. {}.fn()
// 3. re = {name:"jack", birthday:"2001-02-03", life:1, money:0, makeMoney:function}
function fm(name, birthday) {
this.name = name;
return [10, 20,30];
};
var re = new fm("jack");
console.log(re);
// 1. {}
// 2. {}.fm
// {name:"jack"}
// 3. re = [10, 20, 30]
只要是函数就可以new
function fn() {};
var re = new fn();
console.log(re); // fn
任何对象都有构造函数
var re = new Array();
console.log(re); // []
// 1.
function fn() {
this.name = "karen";
return function fm() {
console.log("fm运行了");
this.name = "jack";
}
};
var f1 = new fn();
console.log(f1.name); // fm
var f2 = new(new fn())(); // fm运行了
console.log(name); //
console.log(f2.name); // jack
// 2.
function fn() {
this.name = "marry";
var obj = {
name: "karen",
fm: function () {
this.name = "jack"
}
};
return obj;
};
var f1 = new fn();
console.log(f1.name); // karen
var f2 = new((new fn).fm)();
console.log(f2.name); // jack
var f3 = new fn();
var f4 = new(f3.fm)();
console.log(f3.name, f4.name); // karen jack
// 3.
function Parent() {
this.a = 1;
this.b = [1, 2, this.a];
this.c = {
demo: 5
};
this.show = function () {
console.log(this.a, this.b, this.c.demo); // 4,[1,2,1],3
};
this.change = function () {
this.a = this.b.length;
this.c.demo = this.a++; // ++在后 先取值再加
};
return "hello";
};
var parent = new Parent();
parent.change();
parent.show();