如何使用获取和设置函数 javascript 对象
How to use get and set functions javascript object
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;
}
您可以拿一个对象并为想要的 属性 实施 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);
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;
}
您可以拿一个对象并为想要的 属性 实施 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);