zoukankan      html  css  js  c++  java
  • Object.defineProperty 中 get set 用法

    就是两个函数,只要搞清楚get、set的执行时机就可以了。执行时机如下代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
    </head>
    <body>
        <h1 id="h1"></h1>
        <p id="content"></p>
    </body>
    <script>
      var o = {};
      Object.defineProperty(o,'name',{
        get : function() {
          alert('get');
          return 'kkk';
        },
        set : function (val) {
          alert('set');
          alert('val ---   '+ val); //'Jack'
          // o.name = 'qqq';  // 在这里设置o.name会进入死循环,因为o.name一旦发生变化,就会触发set
          return 'ppp';
        }
      });
    
      // (取值):读取 o 的属性 name 的值,会调用get方法
      var b = o.name;
      console.log(b); // 'kkk'
    
      // (赋值):修改 o 的属性 name 的值,会调用set方法
      // set可以接收一个参数,这个参数就是重新设置的o.name('Jack)
      o.name = 'Jack';
      console.log(o.name); // 'kkk',还是 get 函数中的返回值,set 函数中的返回值没有改变 o.name
    </script>
    </html>
  • 相关阅读:
    1st_pandas
    8thNumpy a.copy()
    7thNumpy array合并
    6th_numpy array的合并 np.vstack np.concatenate np.newaxis
    numpy_5th array索引
    numpy_4th np.transpose(a); a.T ; a.clip(min,max) ; np.sort(a) ; np.diff() ; np.cumsum(a)
    numpy_3rd 布尔运算/乘积点积
    POJ 3270
    POJ 1721
    POJ 3128
  • 原文地址:https://www.cnblogs.com/darkterror/p/8492821.html
Copyright © 2011-2022 走看看