对象声明以及对象所有方法

JavaScript 对象声明以及对象所有方法

对象声明

在JavaScript中,对象可以通过以下几种方式声明:

  • 字面量方式
var obj = { 

  key1: value1,
  
  key2: value2,
  
};

示例:

var person = {

  name: "John",
  
  age: 30,
  
  city: "New York"
};
  • 构造函数方式
function Obj() {
  this.key1 = value1;
  this.key2 = value2;
  ...
}
var obj = new Obj();

示例:

function Person(name, age, city) {
  this.name = name;
  this.age = age;
  this.city = city;
}

var person = new Person("John", 30, "New York");

对象方法

JavaScript对象可以拥有自己的方法(函数)。下面是一些常用的对象方法:

方法声明
  • 字面量方式
var obj = { 
 key1: value1,
 key2: value2,
 method1: function() {
   // 方法体
 },
 method2: function() {
   // 方法体
 },
 ...
};

示例:

var person = {
  name: "John",
  age: 30,
  introduce: function() {
    console.log("My name is " + this.name + ", I'm " + this.age + " years old.");
  }
};
  • 构造函数方式
function Obj() {
  this.key1 = value1;
  this.key2 = value2;
  this.method1 = function() {
    // 方法体
  };
  this.method2 = function() {
    // 方法体
  };
  ...
}

var obj = new Obj();

示例:

function Person(name, age, city) {
  this.name = name;
  this.age = age;
  this.city = city;

  this.introduce = function() {
    console.log("My name is " + this.name + ", I'm " + this.age + " years old.");
  };
}

var person = new Person("John", 30, "New York");

方法调用
可以通过对象访问方法并调用:

obj.method1();

示例:

person.introduce();

示例

var person = {
  name: "John",
  age: 30,
  city: "New York",
  introduce: function() {
    console.log("My name is " + this.name + ", I'm " + this.age + " years old, living in " + this.city + ".");
  },
  increaseAge: function() {
    this.age++;
  }
};

person.introduce(); // 输出:My name is John, I'm 30 years old, living in New York.
person.increaseAge();
person.introduce(); // 输出:My name is John, I'm 31 years old, living in New York.
以上就是JavaScript对象声明以及常用的对象方法的知识整理
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值