Object basic
定义一个简单的对象
let user = {
name: 'Q10Viking',
city: 'BeiJing',
code: function () {
console.log(`${this.name} is learning javascript at ${this.city}`)
}
}
console.log(user.code());
其中需要注意,在对象中定义方法不能使用箭头函数,因为箭头函数没有单独的this,它只会默认的从上一级继承this,MDN Javascript Arrow functions,但是可以简化为这样。
let user = {
name: 'Q10Viking',
city: 'BeiJing',
code() {
console.log(`${this.name} is learning javascript at ${this.city}`)
}
}
Array Object
let user = {
author: 'Q10Viking',
blogs: [
{title: '01-program with javascript',likes: 20},
{title: '02-array object in javascript',likes: 35}
],
code() {
console.log(`The ${this.author} has written the following blogs:`)
this.blogs.forEach((blog)=>{
console.log(blog.title,blog.likes)
})
}
}
// this will be assign by the user object
console.log(user.code());
Math Object
// Math object
let num = 7.7;
// 四舍五入
console.log(Math.round(num));
// 向下取值
console.log(Math.floor(num));
// 向上取值
console.log(Math.ceil(num));
// 去除小数位数
console.log(Math.trunc(num));
// [0,1)随机数
console.log(Math.random());
// 生成[0,100)随机数
let random = Math.random();
console.log(Math.round(random*100));
Primitive & Reference type
primitive 类型存储在stack中,reference类型存储在heap中。
// primitive type
let numOne = 50,numTwo = numOne
// 50 50
console.log(numOne,numTwo);
numOne = 100;
// 100 50
console.log(numOne,numTwo);
// reference type
let userOne = {name: 'Q10Viking'},userTwo = userOne;
// {name: "Q10Viking"} {name: "Q10Viking"}
console.log(userOne,userTwo);
userOne.name="hzz";
// {name: "hzz"}name: "hzz"__proto__: Object {name: "hzz"}
console.log(userOne,userTwo);
遍历属性
for (const key in Object)
如在vue场景中,通过子组件一次性更新父组件的值
data () {
return {
right: {
'crightName': null,
'crightImage': null,
'crightContent': null
}
}
methods:{
handleRights () {
if (this.createNewFlag) {
// create 注意需要返回一个新的对象,如果只是this.right,那么会因为公用一个对象而出错
this.$emit('createNewRight', {...this.right})
} else {
// update 一次性更新
for (const key in this.right) {
this.$emit(`update:${key}`, this.right[key])
}
}
}
}
注意:需要返回一个新的对象,如果只是this.right,那么会因为公用一个对象而出错