js使用函数来创建对象

【直接使用函数创建对象】
使用new替换this指针-----实例化

//构造函数
function pet(name,sex,age){
        this.name=name;
        this.sex=sex;
        this.age=age;
        this.play=function(){
            return"玩耍";
        };
        this.eat=function(){
            return"吃饭";
        };
    }
var bella=new pet();      //使用new替换this指针

函数中的this指向window
这里用new实例化了pet这个函数,构建出了新的对象,替换this指针

在这里插入图片描述
原型链_proto_上的构造constructor指向构造函数pet()本身

实例对象的原型链=函数的原型对象
console.log(bella.proto == pet.prototype);
原型对象的构造指向本身
console.log(pet.prototype.constructor==pet);

【自定义一个new】

//自定义new
function people(name,sex,age){
    this.name=name;
    this.sex=sex;
    this.age=age;
    this.study=function(){
        return"学习";
    };
    this.eat=function(){
        return"吃饭";
    };
}
var New=function(xc){   //构建形参xc
    var obj={};
    console.log(obj);
    obj.__proto__=xc.prototype;  // 让kk的原型链等于形参xc的原型对象
    xc.prototype.constructor=xc;
    console.log(obj);
    //获取属性
    var args=Array.prototype.slice.call(arguments,1);
    //Array数组中的prototype原型中的slice检取方法  call替换对象   argumens
    console.log(args);
    xc.apply(obj,args);
    return obj;
};
New(people);  //将people传给New
var wang=New(people,"jiseng",19,"男");   //传值
console.log(wang);

先自定义一个函数New 在构建一个形参xc
最后在New(people)将函数people传进New中实现实例化
其中args是函数的参数列表值,里面是如下图将传进去的属性值以集合的形式存储
在这里插入图片描述
var args=Array.prototype.slice.call(arguments,1);
数组Array的方法在他的原型prototype对象上
因此要通过取数组上的原型对象才能取到clice方法。
(arguments,1)的意思是截取argument从一开始到完截取

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值