【问题标题】:Javascript Object Literal, Cannot Set PropertiesJavascript 对象文字,无法设置属性
【发布时间】:2014-11-18 15:17:49
【问题描述】:

我正在尝试向我的对象文字添加元素,我收到的只是控制台中的undefined 输出。

为什么 itemSize 被打印为undefined 以及为什么我试图设置的所有属性也未定义。我一定在这里遗漏了一些重要的东西。

我也不明白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 );
           }
 };

【问题讨论】:

  • 因为你没有向函数传递任何值。应该是 new GULE.Scene();
  • 天哪。那么现在这个错误已经解决了,get testFunction 的目的是什么,我不明白它是如何工作的。

标签: javascript object-literal


【解决方案1】:

正确的代码应该是 - var square = new GULE.Scene(5); square.hey( );

【讨论】:

【解决方案2】:

为什么 itemSize 被打印为 undefined...?

因为您没有向Scene 构造函数传递任何内容,所以参数是undefined,这是您分配给itemSize 的值。

get testFunction...的目的是什么?

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

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);
  }
})();

【讨论】:

    猜你喜欢
    • 2015-03-14
    • 2013-04-11
    • 1970-01-01
    • 2018-12-02
    • 2019-07-20
    • 2018-06-05
    • 1970-01-01
    • 2018-09-13
    • 2013-12-23
    相关资源
    最近更新 更多