[英]Why can't a method in the instance of my javascript class see a property
A property set in the constructor of a class is not available to other functions in that instance of the class 在类的构造函数中设置的属性不适用于该类实例中的其他函数
The class constructor takes an object as data as its argument. 类构造函数将一个对象作为数据作为其参数。 This is then saved as a property of the instance - all good.
然后将其保存为实例的属性-一切正常。
const form = new Form({
"name": "John",
"description": "a good bloke",
"box_id": 1
});
I can see that form.orginalData
is the object passed however when I run 我可以看到
form.orginalData
是传递的对象,但是当我运行时
form.toString()
I get an empty object (set in the function called data) 我得到一个空对象(在名为data的函数中设置)
Here is the example in full 这是完整的示例
class Form { constructor(data) { this.orginalData = data for (let field in this.orginalData) { this[field] = data[field]; } } data() { let d = {}; for (let p in this.originalData) { d[p] = this[p]; } return d; } toString() { return JSON.stringify(this.data()); } } const form = new Form({ "name": "John", "description": "a good bloke", "box_id": 1 }); let message = document.getElementById('message'); form.name = 'Ian'; form.description = 'is a wicked man'; message.innerHTML = form.name + '<br/>'; message.innerHTML += form.description + '<br/>'; message.innerHTML += "orginalData:" + JSON.stringify(form.orginalData) + '<br/>' message.innerHTML += "<p>BUT if I run form.data() I get </p>" message.innerHTML += form.toString();
#message { border: 1px solid blue; padding: 10px; } body { font-family: Sans-Serif; }
<h1> Class property persistance </h1> <p> output: </p> <div id="message"> Something went wrong </div>
I am obviously missing something fairly fundamental 我显然缺少了一些基本的东西
您得到空结果,因为originalData与orginalData
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.