我正在尝试解决问题,但我需要了解原型。
我正在阅读,我以为我得到了它,但我仍然有一些并发症
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 ???
所以,当我需要调用该函数时,我的错误是什么?或者它在哪里?
答案 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;