【发布时间】:2016-08-19 23:12:59
【问题描述】:
伙计们!
总的来说,我在 JS 和 OOP 中迈出了第一步,我正在尝试构建代码,可能对我的关卡来说过于程式化,但我希望我的集合变得像“object.a”和“ object.a = value”,而不是称它们为“getA”和“setA”,最重要的是,绝对不像函数(“object.a()”和“object.a(value)”)。
我设计这个页面是为了找到我的做事方式,但这让我发疯:
- 我不知道为什么“wa”会不断增加它的值,直到出现“递归过多”的消息。
- 我不知道如何获取 a 并设置 a 以查看“coso”中的“a”。
谁能帮帮我?
这是我的代码:
<!doctype html>
<html>
<head>
<link href="/style.css" rel="stylesheet" type="text/css">
<meta charset="utf-8">
<style>
</style>
<script>
function coso() {
var a = 1024;
coso.prototype = {
get a() {return this.a},
set a(valor) {this.a = valor}
}
this.muestraA = function() {if(a === this.a) {alert("¡Yupi!")} else alert("A vale: " + a +", pero a vale: " + this.a)}
}
function GuardaA(valor) {
var obj = new coso();
obj.a = valor;
obj.muestraA();
return obj.a;
}
</script>
<title>Prueba Objeto</title>
</head>
<body>
<h1>Prueba Objeto</h1>
<form onchange="x.value=GuardaA(wa.value)">
<label for="wa">Valor para A</label>
<input type="number" id="wa">
<label for="x">A vale:</label>
<output id="x" for="wa"></output>
</form>
<footer></footer>
</body>
</html>
【问题讨论】:
-
var a与this.a不同。 -
你得到了无限递归,因为
this.a调用get a(),它试图读取this.a,它调用get a(),等等。
标签: javascript object scope