JS使用函数创建对象

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script>
    function people(name,age,sex){
        this.name=name;
        this.age=age;
        this.sex=sex;
        this.sleep=function (){
            return "睡觉";
        };
        this.eat=function (){
            return "吃饭";
        }
    }
    var p = new people('张三','21','男');
    console.log(p);

    function work(name,age,sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.sleep = function(){
            return "睡觉奥";
        };
        this.eat = function(){
            return "吃饭";
        }
    }
    var w = new work("大壮",31,"男");
    console.log(w);


    //建立一个ew的匿名函数
    var New  = function(o){
        var obj = {};//创建一个基本对象
        obj.__proto__ = o.prototype;//对象的原型链 = 函数的原型对象
        o.prototype.constructor = o;//函数的原型对象的构造函数指向本身
        //考虑函数的属性和方法   以及传递的参数
        var args = Array.prototype.slice.call(arguments,1);
        o.apply(obj,args);
        return obj;
    }
    var maodou = New(people,"maodou",15,"男");
    console.log(maodou);





    //面试题  自己写一个排序,用数组来执行
    Array.prototype.mySort = function(){
        return this.sort();
    }
    var  str = [2,4,5,1,7,8,6];
    console.log(str.mySort());



    //函数的原型对象
    function Animal(){

    }
    console.log(Animal.prototype);//输出的是当前函数的原型对象
    console.log(Animal.prototype.constructor);//输出的是当前函数原型对象的构造函数 指向本身

    /*原型对象上面可以写入原型方法和原型属性
    * 1.原型属性
    *   Animal.prototype.name = null;
    *   Animal.prototype.age = null;
    *   Animal.prototype.sex = null;
    * 2.原型方法
    *   Animal.prototype.sleep = function(){console.log("睡觉");};
    *   Animal.prototype.eat = function(){console.log("吃饭");};
    *   console.log(Animal.prototype);
    *   */
    //例如:
    Animal.prototype = {
        constructor:Animal,
        name:"",
        age:"",
        sex:"",
        sleep:function(){

        },
        eat:function(){

        }
    }
    console.log(Animal.prototype);
    //原型对象上的属性方法 全是共享的
    var cat = new Animal();
    console.log(cat);
    var mouse = new Animal();
    console.log(mouse);
</script>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值