javascript 中定义类和对象的几种方式

来源:互联网 发布:程序员淘汰 知乎 编辑:程序博客网 时间:2024/04/23 19:09

一.采用json的方式来定义

var xiaoxing = {

grade:1,

name : "xiaoxing",

age:27, sex:"男",

speak:function(words) {

alert(this.name+"说:"+words+"!");

},

improve:function() { this.grade++; }

}

这样,我就变成了一个对象了,你可以让我跟你说一句话

xiaoxing.speak("欢迎");while(i have friends){   xiaoxing.improve();}


 

 

二,在用他的prototype原型对象的方式来定义其属性,事件等,方便继承扩展。 

//创建原型对象,定义属性、方法、及对象事件等。
Student.prototype=
{
    _name:null,
    _age:null,
    _sex:null,
    ShowName:function()
    {
        alert("Name:"+ this._name +"\n" + "Age:" + this._age + "\n" + "Sex:"+ this._sex);
    }
}
//专门用一个函数来初始化对象。
function Student(name,age,sex)
{
    this._name=name;
    this._age=age;
    this._sex=sex;
}

var student=new Student("Young",25,"男"); //实例化
student.ShowName(); //调用对象方法


 

三,构造函数方式

function Student(name,age,sex)
{
    this._name=name;
    this._age=age;
    this._sex=sex;
    this.ShowName=function()
    {
        alert("Name:"+ this._name +"\n" + "Age:" + this._age + "\n" + "Sex:"+ this._sex);
    };
}

var student=new Student("Young",25,"男"); //实例化
student.ShowName(); //调用对象方法

四,这种方式和方式二差不多,采用类得方式来定义

var person = new Function();//或var person = function(){}都可以
person.prototype={
    grade:0,
    age:0,
    sex:null,
    name:null,
    speak:function(words)
    {
        alert(this.name+"说:"+words+"!");
    },
    init:function(_grade,_age,_sex,_name)
    {
        this.grade = _grade;this.age=_age;this.sex=_sex;this.name=_name;
    }
}
var xiaoxing = new person();
xiaoxing.init("10","27","男","xiaoxing");
xiaoxing.speak("hello everybody");

原创粉丝点击