javascript - 'this' 和 'prototype' ,简单函数

标签 javascript

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

我正在阅读,我以为我明白了,但我仍然遇到一些并发症

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 ???

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

最佳答案

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

据我了解,您需要像问候语一样显示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>

关于javascript - 'this' 和 'prototype' ,简单函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31174934/

相关文章:

javascript - 当访问我网站的特定 url 时,如何自动最大化浏览器窗口?

javascript - 如何在对象内形成字段关联?

javascript - Rails js没有执行

javascript - 如何使用javascript将base64转换为二进制流?

javascript - 在哪里可以找到图像的 Instagram 媒体 ID(具有访问 token 并关注图像所有者)?

javascript - 悬停时的图像效果不透明

javascript - 热图按日期隐藏列

Javascript/Firestore : Uncaught (in promise) TypeError: firebase. firestore(...).collection(...).doc(...).collection(...).set 不是函数

javascript - 使用嵌套单选按钮获取父输入 div 的 ID 以实现可访问性

javascript - react : Link to a div on another html page