问题描述
我想创建一个属性,可以调用或不调用。例如:
function Test(){
var obj = {someString:'here is text'};
Object.defineProperty(obj,'string',{
get:function(){
return obj.someString;
},
set:函数(){
返回函数(val){
obj.someString = val;
}
}
});
return obj;
}
var test = new Test();
这样我就可以做到:
test.string //最初返回'here is text'
test.string( 'new text here')//将obj.someString设置为'new text here'
test.string / /返回'下一个文本在这里'
上面的代码目前不按照我希望的方式运行。无论如何在JavaScript中做这样的事情?或者使用 Object.defineProperty 或不使用
您可以使用ES6语法:
class Test {
constructor(){
this.someString =here is text;
}
get string(){
return this.someString;
}
set string(val){
this.someString = val
}
}
I want to make a property either invokable or not. So for example:
function Test () { var obj = { someString: 'here is text' }; Object.defineProperty(obj, 'string', { get: function() { return obj.someString; }, set: function() { return function(val) { obj.someString = val; } } }); return obj; } var test = new Test();
That way I could do:
test.string // initially returns 'here is text'
test.string('new text here') // sets obj.someString to 'new text here'
test.string // returns 'next text here'
The code above does not currently function the way I want it to. Is there anyway to do something like this in JavaScript? Either using Object.defineProperty or not
You can use ES6 syntax:
class Test{ constructor(){ this.someString = "here is text"; } get string(){ return this.someString; } set string(val){ this.someString = val } }
这篇关于制作一个属性,可以调用或不调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!