首页 > Web开发 > 详细

Js定义类或对象

时间:2014-03-08 13:55:23      阅读:494      评论:0      收藏:0      [点我收藏+]

一、工厂方法

 1.原始

  var stu = new Object();

  stu.name = "张三";

  stu.age = 10;

  stu.getName = function(){

      return this.name;

}

2.解决

 function createStudent(){

   var stu = new Object();

   stu.name = "张三";

   stu.age = 10;

   stu.getName = function(){

      return this.name;

}

return stu;

}

3.传参数

function createStudent(name,age){

    var stu = new Object();

    stu.name = name;

    stu.age = age;

    stu.getName = function(){

        return this.name;

    }

    return stu;

}

 

二、构造函数与原型

   1.构造函数

    function Student(name,age){

      this.name = name;

      this.age = age;

      this.getName = function(){

          return this.name;

    }

}

   2.原型

      function Student(){}

      Student.prototype.name = "张三";

      Student.prototype.age = 10;

      Student.prototype.getName = function(){

           return this.name;

    }

  3.构造函数+原型

    function Student(name,age){

      this.name = name;

      this.age = age;

    }

    Student.prototype.getName = function(){

       this.name;

    }

Js定义类或对象,布布扣,bubuko.com

Js定义类或对象

原文:http://www.cnblogs.com/ai3xiaoyi/p/3587131.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!