简体   繁体   English

为什么我的javascript类实例中的方法看不到属性

[英]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.

相关问题 为什么我在JavaScript中看不到字符串的.value属性? - Why don't I see the .value property for my string in javascript? 为什么在类方法中使用我的实例属性时未定义? - Why is my instance property undefined when used in a class method? 为什么我的CoffeeScript类中的函数不能“看到”其他? - Why can't the functions in my CoffeeScript class 'see' other? 为什么我的JavaScript无法看到选择了哪个html选项 - Why can't my javascript see which html option is selected 在Javascript中,为什么我无法绘制我的对象的多个实例? - In Javascript, why I can't draw multiple instance of my object? 为什么我看不到 onclick 属性? - Why I can't see onclick property? 为什么我无法在我的 class 中访问此属性 - Why I can't acces this property in my class 为什么在JS继承中无法从子类实例访问父类的属性? - Why I can't access a property of parent class from child class instance in JS inheritance? 为什么当我在此JavaScript对象上使用反射时,看不到其原型对象中定义的属性? - Why when I use reflection on this JavaScript object I can't see a property defined in its prototype object? JavaScript错误,但看不出原因 - JavaScript errors, but can't see why
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM