[英]Setting an object's value
I'm toying around with objects in javascript since I'm learning how to do OOP in JavaScript, and coming from C#, I see it is a quite different story in here.我正在玩 javascript 中的对象,因为我正在学习如何在 JavaScript 中执行 OOP,并且来自 C#,我看到这里是一个完全不同的故事。
Here's my code so far:到目前为止,这是我的代码:
/*JavaScript Objects*/
var employee = new Object();
employee.firstName = "";
employee.lastName = "";
employee.salary = "";
employee.vacationDays = "";
employee.age = "";
employee.yearsWorking = "";
var getFirstName = function(firstName){
this.value = firstName;
}
I'm not sure if the function is well put, and what I'm doing now, is going to console on Chrome and setting the firstName by calling the function like this:我不确定这个函数是否放置得很好,我现在正在做的是在 Chrome 上进行控制台并通过调用这样的函数来设置 firstName:
employee.getFirstName("Brandon");
But for some reason, the property firstName
is still ""
.但出于某种原因,属性firstName
仍然是""
。 Any thoughts on anything I can be doing wrong here?对我在这里可能做错的任何事情有什么想法吗?
Change this.改变这个。
var getFirstName = function(firstName){
this.value = firstName;
}
To:到:
employee.getFirstName = function(firstName){
this.firstName= firstName;
}
I know that answering with just a link is not the preferred way in SO but I don't think it is possible to transfer the necessary knowledge in just a few sentences - at least I'm not able to to do it in this case.我知道仅用链接回答不是 SO 中的首选方式,但我认为仅用几句话就可以传递必要的知识 - 至少在这种情况下我无法做到。
This page will guide you through your path from C# to OO javascript此页面将引导您完成从 C# 到 OO javascript 的路径
it looks like you are trying to set a value with a function named "getFirstName" try that:看起来您正在尝试使用名为“getFirstName”的函数设置一个值,请尝试:
employee.getFirstName = function(firstName){
this.firstName = firstName;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.