JavaScript中面向对象的编程方法

 以下给出了一个例子,可以自定义一个对象。为其添加属性,添加相关的方法。

 

自己编写这样一个文件(User.js):

  1. function User(name, age) {
  2.    // 成员变量
  3.    this.name = name;
  4.    this.age = age;
  5.    
  6.    // 成员方法
  7.    this.getName = function() {
  8.       return this.name;
  9.    };
  10.    
  11.    this.getAge = function() {
  12.        return this.age;
  13.    };
  14.    
  15.    this.setName = function(name) {
  16.        this.name = name;
  17.    };
  18.    
  19.    this.setAge = function(age) {
  20.        this.age = age;
  21.    };
  22. }
  23. function main() {
  24.    var user = new User("name111", 18);
  25.    document.writeln("fir name = " + user.getName());
  26.    document.writeln("fir age = " + user.getAge());
  27.    document.writeln("<br><br>");
  28.    user.setAge(20);
  29.    user.setName("new name222222");
  30.    document.writeln("fir name = " + user.getName());
  31.    document.writeln("fir age = " + user.getAge());
  32. }

    自己定义了一个User类,添加类的属性和方法。并通过main函数进行测试调用。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值