在Javascript定义对象
var xiaoxing = { grade:1, name : "xiaoxing", age:27, sex:"男", speak:function(words) { alert(this.name+"说:"+words+"!"); }, improve:function() { this.grade++; } } xiaoxing.speak("欢迎来到cnblogs的supersun的天空"); while(i have friends) { xiaoxing.improve(); }
<script language="javascript" type="text/javascript"> //创建原型对象,定义属性、方法、及对象事件等。 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(); //调用对象方法 </script>
三
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <META NAME="Generator" CONTENT="EditPlus"> <META NAME="Author" CONTENT=""> <META NAME="Keywords" CONTENT=""> <META NAME="Description" CONTENT=""> </HEAD> <BODY> <script language="javascript" type="text/javascript"> 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(); //调用对象方法 </script> </BODY> </HTML>
四
<script type="text/javascript"> 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"); </script>
这里采用init来初始化定义了一个对象,当然我们还可以在function(){}这样写
var person = function(_grade,_age,_sex,_name){this.grade = _grade;this.age=_age;this.sex=_sex;this.name=_name;} var xiaoxing = new person("10","27","男","xiaoxing"); xiaoxing.speak("hello everybody"); |