对象的声明方式
1.字面量的方式声明对象:由一对大括号括起来
var obj = {
属性名称:属性值,
方法名称:function (){
//函数执行体
}
}
复制代码
2.new 操作符+Object 声明对象:
var obj = new Object();
obj.属性名称 = 属性值;
obj.方法名称 = function (){
//函数执行体
}
复制代码
3.构造函数声明对象:
在 function 中用 this 引用当前对象,通过对属性的赋值来声明属性。如果用var声明变量,则该变量为局部变量,只允许在类定义中调用。
function text([参数列表]){
this.属性名称 = 属性值;
this.方法名称 = function (){
//函数执行体
}
}
var obj = new text(参数);
复制代码
function myClass() {
this .id = 5 ;
this .name = ' myclass ' ;
this .getName = function () {
return this .name;
}
}
var my = new myClass();
alert(my.id); //5
alert(my.getName());//myclass
复制代码
4、工厂方式声明对象:
function text(name, age){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.run = function (){
return this.name + this.age;
}
}
var obj1 = text('zhaoweinian', 21);
var obj2 = text('lisi', 30);
复制代码
function myClass() {
var obj =
{
' id ' : 2 ,
' name ' : ' myclass '
};
return obj;
}
function _myClass() {
var obj = new Object();
obj.id = 1 ;
obj.name = ' _myclass ' ;
return obj;
}
var my = new myClass();
var _my = new _myClass();
alert(my.id);//2
alert(my.name);//myclass
alert(_my.id);//1
alert(_my.name);//_myclass
复制代码
5.原型模式声明对象:
function text(name, age){
text.prototype.属性名称 = 属性值;
text.prototype.方法名称 = function (){
//函数执行体
}
}
var obj = new text('lisa', 20);
复制代码
6.混合模式声明对象:
function text(name, age){
this.name = name;
this.age = age;
}
text.prototype.属性名称 = 属性值;
text.prototype.方法名称 = function (){
//函数执行体
}
var obj = new text('zhangsan', 30);
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END