Javascript 对象文字,无法设置属性

标签 javascript object-literal

我正在尝试将元素添加到我的对象文字中,但我收到的只是控制台中的未定义输出。

为什么 itemSize 被打印为 未定义 以及为什么我尝试设置的所有属性也未定义。我一定错过了一些大事。

我也不明白 get testFunction 的目的以及如何访问它,因为它似乎没有遵循在函数名称后面有冒号的其他函数的签名。

我现在很困惑。

index.html

var square = new GULE.Scene();
square.hey( 5 );

gule.js

 var GULE = GULE || {};

 GULE.Scene = function ( itemSize ) {

  this.itemSize = itemSize;
  console.log( "Trying in constructor: " + this.itemSize );
  console.log( "Passed variable: " + itemSize );

 };

 GULE.Scene.prototype = {

      constructor: GULE.Scene,
      stuff: 1,
      get testFunction () {
            console.log( "testFunction!" );
          },
      add: function () {
              this.stuff += 1;
            },
      hey: function () {
              console.log( this.stuff );
              console.log( "Trying in function: " + this.itemSize );
           }
 };

最佳答案

Why is itemSize being printed as undefined...?

因为您没有将任何内容传递到 Scene 构造函数中,所以参数是 undefined,这就是您分配给 itemSize 的内容>.

what is the purpose of the get testFunction...?

它创建一个名为 testFunction 的属性,当访问该属性时,会调用一个函数;请参阅§11.1.5规范的。这是 ES5 的一项功能。如果打开 Web 控制台,然后在创建 square 后执行此操作:

var x = square.testFunction;

...你会看到“testFunction!”在控制台中,因为您访问了该属性。

当您阅读 testFunction 时看到 undefined 的原因是 getter 定义的函数不返回任何内容。

这是一个更清晰的示例:

(function() {
  "use strict";
  
  var obj = (function() {
    var propValue = "Initial value";
    
    return {
      normalProp: 42,
      get accessorProp() {
        display("Reading accessorProp");
        return propValue;
      },
      set accessorProp(value) {
        display("Writing accessorProp, new value: " + value);
        propValue = value;
      }
    };
  })();
  
  display("normalProp is " + obj.normalProp);
  display("accessorProp is " + obj.accessorProp);
  obj.accessorProp = "Testing";
  display("accessorProp is now " + obj.accessorProp);

  function display(msg) {
    var p = document.createElement("p");
    p.innerHTML = String(msg);
    document.body.appendChild(p);
  }
})();

关于Javascript 对象文字,无法设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26011659/

相关文章:

javascript - 通过正则表达式进行文件验证 - Javascript

javascript - x 的变量在 transit.js 中不起作用

javascript - 用于在多个表单提交和页面更新中持续存在的用户可修改列表的网页设计模式?

javascript - ReactJS 需要根据逻辑有条件地显示不同的 onclick 和 Link

javascript - 对象文字表示法中的方法记录到控制台,但也记录未定义

javascript - 悬停在节点上时显示节点内的复选框

javascript - 找到总和为给定数字的唯一数字对的所有索引的最小总和

JavaScript 面向对象编程 :reach the method inside object

javascript - 使用 javascript/jQuery 向元素添加标题的最有效方法

javascript - $scope 在 $apply() 之后没有刷新模板内的数据