以下给出了一个例子,可以自定义一个对象。为其添加属性,添加相关的方法。
自己编写这样一个文件(User.js):
- function User(name, age) {
- // 成员变量
- this.name = name;
- this.age = age;
- // 成员方法
- this.getName = function() {
- return this.name;
- };
- this.getAge = function() {
- return this.age;
- };
- this.setName = function(name) {
- this.name = name;
- };
- this.setAge = function(age) {
- this.age = age;
- };
- }
- function main() {
- var user = new User("name111", 18);
- document.writeln("fir name = " + user.getName());
- document.writeln("fir age = " + user.getAge());
- document.writeln("<br><br>");
- user.setAge(20);
- user.setName("new name222222");
- document.writeln("fir name = " + user.getName());
- document.writeln("fir age = " + user.getAge());
- }
自己定义了一个User类,添加类的属性和方法。并通过main函数进行测试调用。