三、面向对象和常用对象
三、面向对象和常用对象
1. 面向对象
1.1 对象简介
在JavaScript中所有的事物都是对象,对象拥有属性和方法。
-
访问对象的属性:
"use strict"; var person = { name: 'xiaoMing' } console.log(person.name) -
访问对象的方法:
"use strict"; var person = { name: 'xiaoMing', like: function (){ console.log('play game.'); } } person.like();
1.2 对象的创建
对象的创建有两种方式,一种是使用Object类,另一种是直接创建。
-
使用Object创建出对象,然后再添加属性和方法
"use strict"; let person = Object(); person.name = 'xiaoMing'; person.like = function (){ console.log('play game'); } -
直接使用{}创建对象并包含属性和方法
"use strict"; var person = { name: 'xiaoMing', like: function (){ console.log('play game.'); } }
1.3 对象构造器
与Java的构造函数一样,在JavaScript中也可以先创建一个模版(构造器),再通过模版去创建一个个对象。
"use strict";
function person(name, like){
this.name = name;
this.like = like;
}
let xh_name = 'xiaoHong';
let like = function (){
console.log('play game');
}
let xh = new person(xh_name, like);
console.log(xh.name);
xh.like();
1.4 apply()
通过apply方法可以使用同一个方法,对不同的对象做处理;有点多态的意思:
"use strict";
let person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
let person1 = {
firstName: "Bill",
lastName: "Gates",
}
let person2 = {
firstName: "Harry",
lastName: "Potter",
}
console.log(person.fullName.apply(person1));
console.log(person.fullName.apply(person2));
2. 常用对象
2.1 Date
var now = new Date(); --> undefined
now.getDate(); --> 6
now.getTime(); --> 1617701582129
now.toString(); --> "Tue Apr 06 2021 17:33:02 GMT+0800 (中国标准时间)"
now.toTimeString(); --> "17:33:02 GMT+0800 (中国标准时间)"
...
2.2 JSON
var xh = {name: 'xiaoHone', age: 18}
JSON.stringify(xh) --> "{"name":"xiaoHone","age":18}" // json对象转为json字符串
var xm = '{"name":"xiaoMing","age":20}'
JSON.parse(xm) --> {name: "xiaoMing", age: 20} // json字符串转换为json对象

浙公网安备 33010602011771号