javascript创建对象,以及实现继承的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_34492035/article/details/70059690

Javascript创建对象


常用的主要有三种模式:

  • 工厂模式
  • 构造函数模式
  • 原型模式

当然还有一些组合的模式,最常用的就是组合使用构造函数模式和原型模式,javascript高级程序设计一书有详细介绍。

  • 工厂模式
    用代码比较能说明,代码如下:

    function createAnimal(name,age){
            var a=new Object();
            a.name=name;
            a.age=age;
            a.run=function(){
                alert(this.name+"is running!");
            }
    }
    var animal01 = createAnimal("cat",2);
    
这种方式呢,是通过一个函数,来创建一个空对象,然后赋予属性,方法,然后再把这个对象作为函数的返回值,这个调用这个函数就能创建对象了。工厂模式虽然解决了创建多个相似对象的问题,但却没有解决对象识别的问题(即怎样知道一个对象的类型),所以便有了构造函数模式
  • 构造函数模式
    可以创建自定义的构造函数,从而定义自定义对象类型的属性和方法。

    function  Person(name,age,job){
        this.name=name;
        this.age=age;
        this.job=job;
        this.eat=function(){
            alert(this.name+'is eatting!');
        }
    }
    

    //实例

    var person1=new Person('xiaoming',18,'student');
    var person2=new Person('xiaohong',18,'student');
    

创建自定义的构造函数意味着将来可以将它的实例标识为一种特定的类型; 而这正是构造函数模式胜过工厂模式的地方。

  • 原型模式
    我们创建的每个函数都有一个 prototype (原型)属性,这个属性是一个指针,指向一个对象,而这个对象的用途是包含可以由特定类型的所有实例共享的属性和方法。如果按照字面意思来理解,那么 prototype 就是通过调用构造函数而创建的那个对象实例的原型对象。使用原型对象的好处是可以让所有对象实例共享它所包含的属性和方法。换句话说,不必在构造函数中定义对象实例的信息,而是可以将这些信息直接添加到原型对象中,例子如下:

    function Person(){
    }
    Person.prototype.name = "Nicholas";
    Person.prototype.age = 29;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function(){
        alert(this.name);
    };
    var person1 = new Person();
    person1.sayName(); //"Nicholas"
    var person2 = new Person();
    person2.sayName(); //"Nicholas"
    alert(person1.sayName == person2.sayName); //true
    

Javascript中的继承

通过原型方式继承

//-----继承的第一种方法:通过借助一个中间对象来实现正确的原型链
    //Parent的构造函数
    function Parent(name,age){
        this.name=name;
        this.age=age;
        this.say=function(){
            alert("I am Parent private function!!");
        }
    }
    Parent.prototype.study=function(){
        alert("我是Praent原型上的函数!");
    }
    //child的构造函数
    function Child(name,age){
        this.name=name;
        this.age=age;
        this.say=function(){
            alert("I am child private function!!");
        }
    }



    function F(){};//空函数F

    F.prototype=Parent.prototype;//把F的原型指向Parent的原型

    Child.prototype=new F();//把child的原型指向一个新的F对象,F对象的原型正好指向Parent.prototype:

    Child.prototype.constructor=Child;//把Child的原型的构造函数修复为Child:

    var aaa=new Child();
    aaa.say();
    aaa.study();    
    //----------可以把继承封装成一个函数inherits(),隐藏中间函数F,优化代码
   function inherits(child,parent){
        var f=function (){};
        f.prototype=parent.prototype;
        child.prototype=new f();
        child.prototype.constructor=child;
   }

   inherits(Child,Parent);
   var bbb=new Child();
   bbb.study();

猜你喜欢

转载自blog.csdn.net/sinat_34492035/article/details/70059690
今日推荐