Home > Web Front-end > JS Tutorial > body text

What are the methods of object definition in javascript

青灯夜游
Release: 2021-10-15 15:15:05
Original
5375 people have browsed it

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([参数列表]){
     方法体
}
Copy after login

Code example:

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

2. Initialization definition:

Creation syntax:

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

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();
Copy after login

3. Constructor type

Creation syntax:

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

Code sample:

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

[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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!