Home  >  Article  >  Web Front-end  >  What are the methods of object definition in javascript

What are the methods of object definition in javascript

青灯夜游
青灯夜游Original
2021-10-15 15:15:055352browse

Definition method: 1. Use the "var object variable name = new Object();" statement; 2. Use the "var object variable name = {...}" statement; 3. Use the "function constructor ([Parameter list]){...}var object name=new constructor([Parameter list]);" statement.

What are the methods of object definition in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Methods to define objects in javascript

1. Direct definition

Creation syntax:

var 对象变量名 = new Object();
对象变量名.属性1 = 属性值1;
…;
对象变量名. 属性N = 属性值N;
对象变量名. 方法1 = function([参数列表]){
	方法体
}
…;
对象变量名. 方法N = function([参数列表]){
     方法体
}

Code example:

	var student = new Object();
	student.name="Lucy";
	student.eat=function(){
		console.log(this.name+"正在吃东西");
	}
	student.eat();

2. Initialization definition:

Creation syntax:

var 对象变量名={
	属性1:属性值1,
	...,
	属性N:属性值N,
	方法1:function([参数列表]){
		方法体
	},
	...,
	方法N:function([参数列表]){
		方法体
	}
}

Note:
1. Use: (English colon) to define attributes
2. Use, (English comma) to separate the attributes and methods of the object, and do not add

# to the last one.
##Code example:

var student = {
   	name:"Tim",  //注意属性的定义用:
   	age:12,
   	eatting:function(){
   		console.log(this.name+"正在吃东西");
   	},
   	running:function(){
   		console.log(this.name+"正在跑步");
   	}
};
student.eatting();
student.running();

3. Constructor type

Creation syntax:

function 构造函数([参数列表]){
	this.属性1=属性值;
	...;
	this.属性N=属性值;
	this.方法1=function([参数列表]){
		方法体
	};
	...;
	this.方法N=function([参数列表]){
		方法体
	};
}
var 对象名 = new 构造函数([参数列表]);

Code sample:

function Student(name){
	this.name=name;
	this.eatting=function(){
		console.log(this.name+"正在吃东西");
	};
}
var stu = new Student("Lily");
stu.eatting();

[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of What are the methods of object definition in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn