js使用函数来创建对象

一、使用函数创建对象

js编程 es5中没有class类,只有function, es6向后端靠拢,才出现了类

function people() {
        this.name = "";
        this.age = "";
        this.sex = "";
        this.sleep = function () {
            return "睡觉";
        }
        this.eat = function () {
            return "吃饭";
        }
    }

    //直接这样使用,this指向window
    //people();
    //使用new关键字,会创建对象
    var xiaoming = new people();
    console.log(xiaoming);
    //有了对象,就可以对象点取出属性和方法了
    console.log(xiaoming.sleep());

 

    //实例对象的原型链==函数的原型对象
    console.log(xiaoming.__proto__ == people.prototype);
    //函数原型对象的构造函数指向本身
    console.log(people.prototype.constructor==people);

二、自己构建一个new

function people() {
        this.name = "";
        this.age = "";
        this.sex = "";
        this.sleep = function () {
            return "睡觉";
        };
        this.eat = function () {
            return "吃饭";
        }
    }

    var New = function (o) {
        var obj = {};

        console.log(obj);
    };
    New(people);

此时输出一个空对象,要想和new出的新对象一样,需要:对象的原型连=函数的原型对象,函数的原型对象的构造函数指向本身,于是就有下面的代码

    var New = function (o) {
        var obj = {};

        obj.__proto__ = o.prototype;
        o.prototype.constructor = o;
        
        console.log(obj);
    };
    New(people);

又考虑到还要有原函数的属性和方法,于是有下面的代码

    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;
    };
    console.log(New(people));

至此,自己构建的对象就与new出的对象就一致了,以上就是new做的事情

三、函数的原型对象

原型对象上可以写入原型方法和原型属性

    function Animal() {

    }

    //原型属性
    Animal.prototype.sex="";
     Animal.prototype.age="";
     Animal.prototype.name="";

     //原型方法
     Animal.prototype.eat=function (){
     console.log("吃饭");
     }
     Animal.prototype.sleep=function (){
     console.log("睡觉");
     }

     console.log(Animal.prototype);

还可以写成下面这样

    function Animal() {

    }

    Animal.prototype = {
        name: "",
        age: "",
        sex: "",
        constructor: Animal,
        sleep: function () {

        },
        eat: function () {

        }
    }

     console.log(Animal.prototype);

原型对象上的属性和方法全是共享的

    var cat = new Animal();
    console.log(cat);
    var mouse = new Animal();
    console.log(mouse);

猜你喜欢

转载自blog.csdn.net/zzo12345/article/details/112814931
今日推荐