https://www.w3schools.com/js/js_object_accessors.asp
在此页面上显示,一个对象可以在javascript中实现get和setter。但是他们使用与我的代码不同的方式来创建对象。如何在以下代码中实现get和setter方法:
function Settings()
{
var fullscreen;
// get function
this.fullScreen = function ()
{
if(fullscreen === undefined)
{
return false
}
return fullscreen;
};
// set function
this.fullScreen = function (fullscrn)
{
fullscreen = fullscrn;
};
// I want to call the set like this: settingsobj.fullScreen = false;
// I want to call the get like this: var myvar = settingsobj.fullScreen;
}
答案 0 :(得分:1)
您可以获取一个对象,并为想要的属性实现setter / getter。
var object = {
fc: undefined,
get fullscreen () { return this.fc === undefined ? false : this.fc; },
set fullscreen (v) { this.fc = v; }
}
console.log(object.fullscreen);
object.fullscreen = 1080;
console.log(object.fullscreen);
具有一个实例和一个provat变量以及它的getter和setter。
class Settings {
constructor() {
var fc;
Object.defineProperty(this, 'fullscreen', {
get () { return fc === undefined ? false : fc; },
set (v) { fc = v; }
});
}
}
var instance = new Settings;
console.log(instance.fullscreen);
instance.fullscreen = 1080;
console.log(instance.fullscreen);