需要对象比较帮助

时间:2015-11-20 01:32:23

标签: javascript

我想比较名称,如果它们匹配,那么说我们有相似的名字,否则我们有不同的名字。但是这段代码在比较名称时会给出输出undefined

有人可以帮助我理解/解决这个问题吗?

我希望得到关注,例如:

  

我们有不同的名字,鲍勃和我。

function addPersonMethods(obj){
    this.obj = obj;
}

addPersonMethods.prototype.greet = function(str){
    return str + ", my name is "+ this.obj.name;
}

addPersonMethods.prototype.nameshake = function(othername){
    this.othername = othername;
    if (this.obj.name == this.othername){
         console.log("We have the same name ," + this.obj.name + " and I! ");
    }
    else
         console.log("We have different names ," + this.obj.name + " and I.");
}

var bob_def =  { name: 'Bob', age: 21 };
var eve_def =  { name: 'Eve', age: 21 };

var bob = new addPersonMethods(bob_def);
var eve = new addPersonMethods(eve_def);
var another_bob = new addPersonMethods({name:'Bob', age: 40});

console.log(bob.greet("Hi all"));
console.log(eve.greet("Hello"));
console.log(another_bob.greet("Hey"));

console.log(bob.nameshake(eve));

2 个答案:

答案 0 :(得分:2)

您的nameshake()方法需要string(名称),但您传递的是对象,因此比较永远不会是true。您想要与该对象.obj.name进行比较。

其次,当函数没有实际返回任何内容时,您将记录bob.nameshake()的结果。

并且您已经在"中打印了自己的名称。我们有......"声明,当你想要打印其他人时。



function addPersonMethods(obj) {
  this.obj = obj;
}

addPersonMethods.prototype.greet = function(str) {
  return str + ", my name is " + this.obj.name;
}

addPersonMethods.prototype.nameshake = function(otherperson) {
  var othername = otherperson.obj.name;

  if (this.obj.name == othername) {
    console.log("We have the same name, " + othername + " and I! ");
  } 
  else
    console.log("We have different names, " + othername + " and I.");
}


var bob_def = {
  name: 'Bob',
  age: 21
};
var eve_def = {
  name: 'Eve',
  age: 21
};


var bob = new addPersonMethods(bob_def);
var eve = new addPersonMethods(eve_def);
var another_bob = new addPersonMethods({
  name: 'Bob',
  age: 40
});

console.log(bob.greet("Hi all"));
console.log(eve.greet("Hello"));
console.log(another_bob.greet("Hey"));

bob.nameshake(eve);
bob.nameshake(another_bob);




答案 1 :(得分:2)

您正在将字符串(this.obj.name)与对象(othername)进行比较。它们将不相等,因此您将始终输出它们具有不同的名称。默认情况下,任何函数的返回值都是undefined,除非您另行指定,这就是undefined将输出拖尾的原因。

eve.obj.name传递给函数,或者在函数内提取该值,以便正确比较。