'这'和'原型',简单的功能

时间:2015-07-02 03:03:20

标签: javascript

我正在尝试解决问题,但我需要了解原型。

我正在阅读,我以为我得到了它,但我仍然有一些并发症

function Person(name){
  this.name = name;
}

Person.prototype.greet = function(otherName){
  return "Hi " + otherName + ", my name is " + name;
}

var kate = new Person('Kate'); //name
var jose = new Person('Jose'); //otherName ???

所以,当我需要调用该函数时,我的错误是什么?或者它在哪里?

1 个答案:

答案 0 :(得分:3)

name是对象实例的属性,因此您需要在this.name方法中使用greet

据我了解,您需要像问候语一样显示Hi Jose, my name is Kate。在这种情况下,您需要将other person传递给greet方法,然后您可以使用object.name

访问该人员姓名



function Person(name) {
  this.name = name;
}

Person.prototype.greet = function(other) {
  return "Hi " + other.name + ", my name is " + this.name;
}

var kate = new Person('Kate');
var jose = new Person('Jose');

snippet.log(kate.greet(jose));

<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;