我正在尝试将元素添加到我的对象文字中,但我收到的只是控制台中的未定义
输出。
为什么 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/