JSON对象使用场景以及this 关键字的几个方法
2019-08-30 22:30 孤城凉梦 阅读(1194) 评论(0) 编辑 收藏 举报-
JSON.parse
是将 json 格式的字符串转换为 js 的对象或者数组var obj = {
name: 'Jack',
age: 18,
gender: '男'
}
var arr = [
{
name: 'Jack',
age: 18,
gender: '男'
},
{
name: 'Jack',
age: 18,
gender: '男'
},
{
name: 'Jack',
age: 18,
gender: '男'
}
]
var jsonObj = JSON.stringify(obj)
var jsonArr = JSON.stringify(arr)
console.log(jsonObj)
console.log(jsonArr)
对象深克隆
var obj = {
a:10,
b:20,
c:{
a:10
}
};
var obj2 = JSON.parse(JSON.stringify(obj));
console.log(obj2);
obj2.c.a=20;
alert(obj.c.a);//10-
jsonObj
就是 json 格式的对象字符串 -
jsonArr
就是 json 格式的数组字符串
-
使用场景:
1,对象的深克隆
2,缓存的存储
3,前后台数据传输解析
this 关键字 主要用于函数中 不同的场景下 指向不同
//普通函数 window
function fn(){
console.log(this);
}
fn(); //window
//事件函数 指向事件源
var btn = document.querySelector('button');
btn.onclick = function(){
console.log(this);//button 事件源
}
//定时器 中也是window
setInterval(function(){
console.log(this); //window
},1000);
//预保留this
//事件函数中嵌套了内层函数,需要在内层函数中使用this得到事件源(this指向window)
var btn = document.querySelector('button');
btn.onclick = function(){
var _this = this;
setInterval(function(){
console.log(_this);
},1000);
}
//this在对象的方法中,指向 调用这个方法的对象
var obj ={
name:"小明",
act:function(){
console.log(this.name);
},
c:{
name:"小红",
b:function(){
console.log(this.name);
}
}
}
obj.act();
obj.c.b();
call() apply() bind() 可以改变this在函数中的指向
bind方法