2017 바이두전단기술대학-vue원본분석의-동적 데이터 귀속1
1. Object.keys()
Object.keys()
방법은 주어진 대상의 모든 자신의 속성을 일일이 열거할 수 있는 속성 이름으로 구성된 그룹을 되돌려줍니다. 그룹에서 속성 이름의 배열 순서와 사용(for in)
이 이 대상을 순환할 때 되돌아오는 순서가 일치합니다. (순서 일치는 디지털 속성을 포함하지 않습니다) (두 사람의 주요 차이점은 for-in은 원형 체인에서 계승할 수 있는 일일이 열거할 수 있는 대상을 두루 훑어봅니다).let obj = {
name:'dailu',
age:123,
sex:"female"
}
console.log(Object.keys(obj)); //["name", "age", "sex"]
var arr = ["a","b","c"];
console.log(Object.keys(arr)); //["0", "1", "2"]
//
var obj1 = {0:"a",1:"b",2:"c"}
console.log(Object.keys(obj1)); //["0", "1", "2"]
2. Object.defineProperty()
Object.defineProperty()
방법은 한 대상에 새로운 속성을 직접 정의하거나 이미 존재하는 속성을 수정하여 이 대상을 되돌려줍니다.문법: Object.defineProperty(obj,prop,descriptor)
개념:
ECMAScript에는 데이터 속성과 액세서리 속성 두 가지 속성이 있습니다.
1. 데이터 속성
속성 특성은 [[]]로 묶여서 js에서 직접 접근할 수 없습니다. 이 특성들은 자바스크립트 엔진을 실현하기 위한 것입니다.
데이터 속성에는 다음 네 가지 비헤이비어를 설명하는 특성이 있습니다.
[[configurable]]
: delete를 통해 속성을 삭제하여 다시 정의할 수 있는지, 속성의 특성을 수정할 수 있는지, 또는 속성을 액세서리 속성으로 수정할 수 있는지를 나타낸다.[[Enumerable]]
: 이 속성의enumerable가true일 때만 이 속성은 대상의 매거 속성에 나타날 수 있다[[Writable]]
: 속성을 수정할 수 있는지를 나타내는 값[[Value]]
: 속성의 값을 나타낸다.주: 대상에 직접 정의된 속성의 세 번째 특성의 기본값은true입니다.
Object.defineProperty()
를 통해 속성을 정의하거나 원래 속성을 수정합니다.예를 들면 다음과 같습니다.
var obj = {}
Object.defineProperty(obj,"name",{
configurable:false,
writable:false,
enumerable:true,
value:'elva'
})
console.log(obj.name); //elva
delete obj.name
console.log(obj.name); //elva
obj.name = 'haha'
console.log(obj.name);//elva
for(var key in obj){
console.log(key) //name
}
configurable
false로 설정하면 writable를 제외한 다른 기능은 수정할 수 없습니다. 수정을 시도하면 (writable 이외에) 현재 값이 수정 값과 같지 않으면 TypeError
이상이 발생합니다.var obj = {}
Object.defineProperty(obj,"name",{
configurable:false,
writable:false,
enumerable:true,
value:'elva'
})
/*
Object.defineProperty(obj,"name",{
enumerable:false // Uncaught TypeError: Cannot redefine property: name
})
*/
Object.defineProperty(obj,"name",{
enumerable:true //
})
주: 속성의 configurable가false이면 writable 특성도false로 수정할 수 있습니다.
var obj = {}
Object.defineProperty(obj,"name",{
configurable:false,
writable:false,
enumerable:true,
value:'elva'
})
// Object.defineProperty()
Object.defineProperty(obj,"name",{
// Object.defineProperty confugurable false, Object.defineProperty
writable:true // Uncaught TypeError: Cannot redefine property: name
})
2. 액세서리 속성:
[[configurable]]
: delete를 통해 속성을 삭제하여 다시 정의할 수 있는지, 속성의 특성을 수정할 수 있는지, 또는 속성을 액세서리 속성으로 수정할 수 있는지를 나타낸다.[[Enumerable]]
: 이 속성의enumerable가true일 때만 이 속성은 대상의 매거 속성에 나타날 수 있다[[get]]
: 속성 값을 읽을 때 호출되는 함수입니다. 기본값은 undefined
입니다.[[]set]
: 속성을 쓸 때 호출되는 함수의 기본값은 undefined
입니다.참고: 액세서리 속성은 직접 정의할 수 없습니다.
Object.defineProperty()
정의를 사용해야 합니다.예를 들면 다음과 같습니다.
var book = {
_year:2004,
edition:1
}
Object.defineProperty(book,"year",{
get:function (){
return this._year
},
set:function (val){
if(val>2004){
this.edition +=val-2004
}
}
})
book.year = 2005
console.log(book.edition); // 2
_year:
3. 여러 속성 정의
Object.defineProperties()
예를 들면 다음과 같습니다.var book ={}
Object.defineProperties(book,{
_year:{
configurable:true,
enumerable:true,
writable:true,
value:2004
},
edition:{
configurable:true,
enumerable:true,
writable:true,
value:1
},
year:{
enumerable:true,
get:function (){
return this._year
},
set:function (val){
if(val>2004){
this.edition += val-2004
}
}
}
})
console.log(book._year); //2004
book._year = 2005
console.log(book.edition);// 1
console.log(book.year); // 2005
console.log(book._year); // 2005
book.year = 2005
console.log(book.edition); //2
console.log(book.year);//2005
요약: 데이터 속성과 액세서리 속성은 모두
[[configurable]]
와 [[enumarable]]
, [[writable]]
와 [[value]]
는 데이터 속성에서만 사용할 수 있고, [[get]]
와 [[set]]
는 액세서리 속성에서만 사용할 수 있다.임무 목적
동적 데이터 바인딩은 Vue의 가장 기초적이고 유용한 기능입니다.이 시리즈는 다섯 부분으로 나뉘어 한 걸음 한 걸음 이 기능을 이해하고 실현할 것이다.오케이, 우리 가장 간단한 것부터 시작하자.어떤 대상을 정하면 그 속성의 읽기와 변화를 어떻게 감청합니까?즉, 프로그램이 대상에 접근한 어떤 속성, 또 어떤 속성을 바꿨는지 어떻게 알 수 있습니까?예를 들다.
let app1 = new Observer({
name: 'youngwind',
age: 25
});
let app2 = new Observer({
university: 'bupt',
major: 'computer'
});
// :
app1.data.name // name
app1.data.age = 100; // age, 100
app2.data.university // university
app2.data.major = 'science' // major, science
다음과 같은 Observer를 사용하십시오.
작업 고려 사항
코드 데모:
function Observer(data){
this.data = data;
this.walk(data)
}
var p = Observer.prototype;
//
p.walk = function (obj){
var val,
_this = this;
Object.keys(obj).forEach(function (key){
val = obj[key]
if(typeof val==="object"){
new Observer(val)
}
_this.convert(key,val)
})
}
// getter setter
p.convert = function (key,val){
Object.defineProperty(this.data,key,{
configurable:true,
enumarable:true,
get:function (){
console.log(" "+key);
return val
},
set:function (newVal){
console.log(" "+key);
console.log(" "+key+"="+newVal);
// , , set/get
if(typeof newVal ==="object"){
new Observer(newVal);
}
val = newVal
}
})
}
let data = {
user: {
name: "hello world",
age: "24"
},
address: {
city: "beijing"
}
};
var app = new Observer(data);
console.log(app.data.user);
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.