JS(17)、构造函数

 构造函数

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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值