JavaScript对象

JavaScript的对象是一种无序的集合数据类型,它由若干键值对组成。

对象是一个包含相关数据和方法的集合,下面就是一个简单的对象

1
2
3
4
5
6
7
8
9
10
11
12
var person = {
name : ['Bob', 'Smith'],
age : 32,
gender : 'male',
interests : ['music', 'skiing'],
bio : function() {
alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
},
greeting: function() {
alert('Hi! I\'m ' + this.name[0] + '.');
}//注意这里没有逗号
};

对象与值之间使用:隔开,对象里的string、number、array也叫对象的属性(property),对象里的函数也叫对象的方法(method),上面整个对象被称为对象的字面量(literal)

访问

点表示法

使用.来访问对象里的属性方法

1
2
person.name;
person.age;

对象也可以作为值

1
2
3
4
5
6
name: {
first:'Bob',
last:'Smith'
}
//访问
person.name.first;

括号表示法

1
2
person['age'];
person['name'];

与数组有点类似,不同的是:对象是字符串到值的映射,数组是数字到值的映射

设置值

通过访问的形式修改

1
person.age = 19;

也可以新增一个属性或者函数

1
2
3
4
person.other = 'other';
person.fun = function(){
alert('hello world');
}

括号表示法的优点就是可以动态的设置成员名字

1
2
3
var dataName = 'height';
var dataValue = '1.60cm';
person[dataName] = dataValue;

构造函数与对象

JS不像java那样可以使用class来声明类,而是使用了构造函数的特殊函数来定义

1
2
3
4
5
6
7
8
9
10
11
12
13
//简单定义
function createNewPerson(name) {
var obj = {};
obj.name = name;
obj.greeting = function () {
alert('Hi! I\'m ' + this.name + '.');
}
return obj;
}
//调用
var salva = createNewPerson('salva');
salva.name;
salva.greeting();

但这样定义有点不方便,因为创建一个空对象还要返回它,以下是一个便捷方法

1
2
3
4
5
6
7
8
9
10
//名字注意大写,代表他是一个类(构造函数)
function Person(name) {
this.name = name;
this.greeting = function() {
alert('Hi! I\'m ' + this.name + '.');
};
}
//调用,使用new就会返回对象
var person1 = new Person('Bob');
var person2 = new Person('Sarah');

注意:引用使用new才是才代表使用构造函数,里面的this才会绑定当前对象,为此构造函数名规定大写

封装new

使用createPerson将new封装起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Person(props) {
this.name = props.name || '无名氏';
this.age = props.age || 0;
}
Person.prototype.greeting = function() {
alert('Hi! I\'m ' + this.name + '.');
};
function createPerson(props){
return Person(props || {})
}
// 调用
let p1 = createPerson({
name: 'muyang'
});

优点

  • 不需要new
  • 参数灵活,可以无序,因为是对象

创建对象的其他方式

Object()

1
2
3
4
5
6
7
8
var person1 = new Object();/*这是一个空对象*/
var person1 = new Object({
name : 'Chris',
age : 38,
greeting : function() {
alert('Hi! I\'m ' + this.name + '.');
}
});/*这是一个有属性方法的对象*/

create()

这个方法可以根据现有对象创建新的对象

1
var person2 = Object.create(person1);

方法

对象里的函数叫方法,如

1
2
3
4
5
6
7
8
var xiaoming = {
name: '小明',
birth: 1990,
age: function () {
var y = new Date().getFullYear();
return y - this.birth;
}
};

viewthis

  • 是一个变量,代表当前对象

  • 需要注意的是this在哪定义,调用形式是什么,如果使用xiaoming.age()调用的话this就代表xiaoming;如果函数在外面,如

    1
    2
    3
    4
    5
    6
    7
    8
    9
    function getAge () {
    var y = new Date().getFullYear();
    return y - this.birth;
    }
    var xiaoming = {
    name: '小明',
    birth: 1990,
    age: getAge
    };

    此时如果使用getAge()调用则会代表全局对象,会返回NaN,而且必须采用xiaoming.age()这个形式调用,就算赋值给变量也不行

  • 如果是在对象方法内定义函数,里面的this也会变回全局对象

1
2
3
4
5
6
7
8
9
10
11
var xiaoming = {
name: '小明',
birth: 1990,
age: function () {
function getAgeFromBirth() {
var y = new Date().getFullYear();
return y - this.birth;
}
return getAgeFromBirth();
}
};

​ 此时使用xiaoming.age()也会返回NaN,解决方法就是将this变量存起来传递,或者使用apply()

1
2
3
4
5
6
7
8
9
10
11
12
var xiaoming = {
name: '小明',
birth: 1990,
age: function () {
var that = this;
function getAgeFromBirth() {
var y = new Date().getFullYear();
return y - that.birth;
}
return getAgeFromBirth();
}
};

控制this指向,函数内有一个apply()方法,第一个参数就是this指向的对象,第二个参数是数组,里面对应函数的参数

1
2
3
4
5
6
7
8
9
10
11
12
13
function getAge() {
var y = new Date().getFullYear();
return y - this.birth;
}

var xiaoming = {
name: '小明',
birth: 1990,
age: getAge
};

xiaoming.age(); // 25
getAge.apply(xiaoming, []); // 25, this指向xiaoming, 参数为空

装饰器

在不改变原有结构给函数添加新功能,下面给出一个示例

假如我想给console.log()添加功能:打印当前时间+内容,我可以这样做

1
2
3
4
5
6
oldConsoleLog  = console.log;/*保留原函数*/

console.log = function (arg){
let date = new Date();
return oldConsoleLog(date+'\n'+arg);
}

标准对象

经常会使用这些对象,如Date等等

Date

表示日期和时间

先来看看对象本身

1
2
3
4
5
6
Date()
UTC: function UTC()
length: 7
name: "Date"
now: function now()
parse: function parse()
  • UTC:接收时间参数,返回1970年1月1日UTC 00:00:00(UNIX时间纪元)以来的毫秒数
  • now:返回当前时间从时间纪元以来的毫秒数
  • parse:可以接收字符串的时间,ISO 8601格式

有了一点原型知识,再看一下他的prototype

Date.prototype >folded
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
prototype: {…}
constructor: function Date()
getDate: function getDate()
getDay: function getDay()
getFullYear: function getFullYear()
getHours: function getHours()
getMilliseconds: function getMilliseconds()
getMinutes: function getMinutes()
getMonth: function getMonth()
getSeconds: function getSeconds()
getTime: function getTime()
getTimezoneOffset: function getTimezoneOffset()
getUTCDate: function getUTCDate()
getUTCDay: function getUTCDay()
getUTCFullYear: function getUTCFullYear()
getUTCHours: function getUTCHours()
getUTCMilliseconds: function getUTCMilliseconds()
getUTCMinutes: function getUTCMinutes()
getUTCMonth: function getUTCMonth()
getUTCSeconds: function getUTCSeconds()
getYear: function getYear()
setDate: function setDate()
setFullYear: ƒ setFullYear()
setHours: ƒ setHours()
setMilliseconds: ƒ setMilliseconds()
setMinutes: ƒ setMinutes()
setMonth: ƒ setMonth()
setSeconds: ƒ setSeconds()
setTime: ƒ setTime()
setUTCDate: ƒ setUTCDate()
setUTCFullYear: ƒ setUTCFullYear()
setUTCHours: ƒ setUTCHours()
setUTCMilliseconds: ƒ setUTCMilliseconds()
setUTCMinutes: ƒ setUTCMinutes()
setUTCMonth: ƒ setUTCMonth()
setUTCSeconds: ƒ setUTCSeconds()
setYear: ƒ setYear()
toDateString: ƒ toDateString()
toGMTString: ƒ toUTCString()
toISOString: ƒ toISOString()
toJSON: ƒ toJSON()
toLocaleDateString: ƒ toLocaleDateString()
toLocaleString: ƒ toLocaleString()
toLocaleTimeString: ƒ toLocaleTimeString()
toString: ƒ toString()
toTimeString: ƒ toTimeString()
toUTCString: ƒ toUTCString()
valueOf: ƒ valueOf()
Symbol(Symbol.toPrimitive): ƒ [Symbol.toPrimitive]()
__proto__: Object

使用Date实例化的对象可以有这些方法,太多了我就介绍几个常用的,只需要注意月份从0开始就行了

1
2
3
4
5
6
7
8
9
10
11
var now = new Date();
now; // Date Mon May 25 2020 09:12:00 GMT+0800 (中国标准时间)
now.getFullYear(); // 2020, 年份
now.getMonth(); // 4, 月份,注意月份范围是0~11,4表示5月
now.getDate(); // 25
now.getDay(); // 1, 表示星期一
now.getHours(); // 9, 24小时制
now.getMinutes(); // 12, 分钟
now.getSeconds(); // 0, 秒,我这时间卡得准不准哈哈
now.getMilliseconds(); // 875, 毫秒数
now.getTime(); // 1590370516029, 以number形式表示的时间戳

Date()可以接受毫秒数和时间参数,都可以以本地时间格式显示出来

Math

Math >folded
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Math
E: 2.718281828459045
LN10: 2.302585092994046
LN2: 0.6931471805599453
LOG10E: 0.4342944819032518
LOG2E: 1.4426950408889634
PI: 3.141592653589793
SQRT1_2: 0.7071067811865476
SQRT2: 1.4142135623730951
abs: function abs()
acos: function acos()
acosh: function acosh()
asin: function asin()
asinh: function asinh()
atan: function atan()
atan2: function atan2()
atanh: function atanh()
cbrt: function cbrt()
ceil: function ceil()
clz32: function clz32()
cos: function cos()
cosh: function cosh()
exp: function exp()
expm1: function expm1()
floor: function floor()
fround: function fround()
hypot: function hypot()
imul: function imul()
log: function log()
log10: function log10()
log1p: function log1p()
log2: function log2()
max: function max()
min: function min()
pow: function pow()
random: function random()
round: function round()
sign: function sign()
sin: function sin()
sinh: function sinh()
sqrt: function sqrt()
tan: function tan()
tanh: function tanh()
trunc: function trunc()
Symbol(Symbol.toStringTag): "Math"

Math完全就是一个工具类,没有prototype,比较常用的就是random(),数学不好,就不过多解释了

作者

manu

发布于

2020-04-18

更新于

2023-01-06

许可协议

# 相关文章
  1.JavaScript原型继承
# 推荐文章
  1.ALTER
  2.数据库笔记
  3.微信小程序笔记
  4.动态调试-OD
  5.winPE结构
  6.git指令

:D 一言句子获取中...