我正在学习javascript对象。 我试图输出我的对象的角色,但它输出原型而不是..
function familyMember(role, name, age) {
this.role = role;
this.name = name;
this.age = age;
}
var father = new familyMember("Dad", "Alex", 50);
var mother = new familyMember("Mom", "Nilly", 51);
father.role = function() {
return this.role;
}
document.getElementById("demo").innerHTML = father.role();
<p id="demo"></p>
这就是它为我打印的内容..
“function(){return this.role;}”
答案 0 :(得分:2)
为什么要覆盖
role = "Father"
带
role = function()
当您使用相同的变量名时,它不会神奇地保留字符串和函数。
答案 1 :(得分:2)
father.role = function() {
return this.role;
}
在这个函数中,这是父亲,所以this.role是father.role:函数。您已覆盖该值。您应该将其命名为father.getRole
(或更好familyMember.prototype.getRole
)
答案 2 :(得分:2)
或者定义一个实际返回Role的函数,而不是用函数覆盖它?
function familyMember(role, name, age) {
this.role = role;
this.name = name;
this.age = age;
this.getRole = function() {
return this.role;
}
}
var father = new familyMember("Dad", "Alex", 50);
var mother = new familyMember("Mom", "Nilly", 51);
document.getElementById("demo").innerHTML = father.getRole();
<p id="demo"></p>
答案 3 :(得分:0)
你想要它回归&#34;爸爸&#34;?如果是这样,你需要删除第二部分,并保持这样:
function familyMember(role, name, age) {
this.role = role;
this.name = name;
this.age = age;
}
var father = new familyMember("Dad", "Alex", 50);
var mother = new familyMember("Mom", "Nilly", 51);
document.getElementById("demo").innerHTML = father.role;
答案 4 :(得分:0)
如上面的评论所述,你覆盖了一些东西。我调整了你需要删除一些不需要的代码并更新一些变量名来停止重叠。
private static readonly MyBuffer SBuffer = new MyBuffer();
private static byte[] array = new byte[0];
public byte[] Read(Data data) {
int size = data.ChunkSize;
if (array.Length != size)
{
array = new byte[size];
}
Array.Copy(SBuffer.Latest(size).ToArray(), array, size);
return array;
}
function familyMember(role, name, age) {
this.memberRole = role;
this.memberName = name;
this.memberAge = age;
}
var father = new familyMember("Dad", "Alex", 50);
var mother = new familyMember("Mom", "Nilly", 51);
document.getElementById('demo').innerHTML = father.memberRole
答案 5 :(得分:0)
也就是说,因为你用你的函数覆盖this.role。
只需为您的函数使用其他名称,例如getRole()。
function familyMember(role, name, age) {
this.role = role;
this.name = name;
this.age = age;
}
var father = new familyMember("Dad", "Alex", 50);
var mother = new familyMember("Mom", "Nilly", 51);
father.getRole = function() {
return this.role;
}
document.getElementById("demo").innerHTML = father.getRole();
<p id="demo"></p>