2017 바이두전단기술대학-vue원본분석의-동적 데이터 귀속1

6900 단어

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
    }
    
    
    configurablefalse로 설정하면 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]]는 액세서리 속성에서만 사용할 수 있다.

    임무 목적

  • Getter 및 setter
  • 이해
  • new 이해
  • 작업 설명
  • 이것은'동적 데이터 귀속'시리즈의 첫 번째 문제다.
    동적 데이터 바인딩은 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를 사용하십시오.
  • 전송 매개 변수는 대상만 고려하고 수조는 고려하지 않습니다.
  • new 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);
    
    

    좋은 웹페이지 즐겨찾기