HTML之JavaScript自定义对象总结

在JavaScript中,对象是拥有属性和方法的数据(可以与java中的对象类比)。

JavaScript自定义对象方式有以下7种:直接创建方式、对象初始化器方式、构造函数方法、prototype原型方式、混合的构造函数/原型方式、动态原型方式和工厂模式,这里叙述常用的5种:

备注:例子部分只展示函数体

一、直接创建式

语法结构

var 对象变量名 = new Object();
对象变量名. property1 = value1;
…;
对象变量名. propertyN = valueN;
对象变量名. methodName1 = function([参数列表]){
	//函数体
}
…;
对象变量名. methodNameN = function([参数列表]){
	//函数体
}

例子:

var student = new Object();
student.name="lulu";
student.study=function(){
	console.log(this.name+"正学习");
}
student.study();//执行结果:lulu正在学习

二、对象初始化式

语法结构:

var 对象变量名 = {
	property1 : value1,
	property2 : value2,
	…, 
	propertyN : valueN,
	methodName1 : function([parameter_list]){
		//函数体
	},
	…, 
	methodNameN : function([parameter_list]){
		//函数体
	}
}
 

例子:

var student = { 
	name: "lili",
	study: function() {
		console.log(this.name + "正在学习....");
	}
}
student.study();//执行结果:lili正在学习

三、构造方法式

语法结构:

function 构造函数([参数列表]){ 
	this.属性 = 属性值; 
	…
	this.属性N = 属性值N;
	this.函数1 = method1; 
	…
	this.函数N = methodN; 
}
function method1([参数列表]){
	//函数体
}
…
function methodN([参数列表]){
	 //函数体
}

或者

function  构造函数([参数列表]){ 
	this.属性 = 属性值; 
	…
	this.属性N = 属性值N;
    this.函数1 = function([参数列表]){
		//函数体
    } ;
	…
    this.函数N = function([参数列表]){
		//函数体
    } ;
}

例子:

function Student(name){
	this.name=name;
	this.study=function(){
		console.log(this.name+"正在学习...");
	}
}
var student = new Student("tim");
student.study();//执行结果:tim正在学习

四、prototype原型式

语法结构

function 对象构造器( ){
} 
对象构造器.prototype.属性名=属性值;
对象构造器.prototype.函数名 = function([参数列表]){
 	//函数体
}

例子:

function Student(){			
}
Student.prototype.name="tim";
Student.prototype.study=function(){
	console.log(this.name+"正在学习...");
}
var student=new Student();
student.study();//执行结果:tim正在学习

五、混合(构造方法+原型)式

语法结构:

function 对象构造器([参数列表]){
} 
对象构造器.prototype.函数名 = function([参数列表]){
	//函数体
}

例子:

function Student(name){
	this.name=name;
}
Student.prototype.study=function(){
	console.log(this.name+"正在学习...");
}
var student = new Student("jim");
student.study();//执行结果:jim正在学习
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值