在JS中围绕原型进行包装 [英] Wrapping my head around prototypes in JS

查看:106
本文介绍了在JS中围绕原型进行包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力理解JS中原型的概念,但出于某种原因,我发现它真的令人费解。为什么以及何时使用原型?

I've been trying to understand the concept of prototypes in JS, but for some reason I'm finding it really baffling. Why and when would you use a prototype?

这有什么区别(来自 MDN示例):

What's the difference between this (from this MDN example):

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

Person.prototype.sayHello = function()
{
  alert ('hello');
};

这个:

function Person(gender) {
  this.gender = gender;

  this.sayHello = function() {
    alert('hello');
  };
}

我想我理解如何使用它们,但我不知道为什么我会用它们。也许我错过了一些东西 - 刮得那么 - 很明显我错过了什么!

I think I understand how to use them, but I don't know why I would use them. Maybe I'm missing something - scratch that - CLEARLY I'm missing something!

有人可以解释这两个例子之间的区别以及为什么我应该使用一个其他?

Can someone please explain the difference between those two examples and why I should use one over the other?

谢谢!

推荐答案

原型对于继承非常重要。如果你不需要继承,那么确实没有区别。但是,请考虑这一点:

Prototype is important for inheritance. If you do not need inheritance, then there is really no difference. However, consider this:

function Person(gender) {
 this.gender = gender;

 this.sayHello = function() {
  alert('hello');
 };
}

function User(){

}

用户如何成为?这里真的没有简单的方法。但是,这可以通过原型实现:

How can a User be a Person? There is really no easy way here. However, this is possible with prototype:

jsFiddle演示

jsFiddle Demo

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

Person.prototype.sayHello = function() {
  alert(this.name);
 };

function User(name){
 this.constructor(name);
}

User.prototype = new Person();

var u = new User("joe");
u.sayHello();//alerts joe

现在,我们可以更进一步,并在使用这样的原型时覆盖为用户打招呼的功能:

Now, we can go even further, and override the functionality of saying hello for User when using prototype like this:

jsFiddle演示

jsFiddle Demo

User.prototype.sayHello = function(){ 
 alert("Username: " + this.name);
}

这篇关于在JS中围绕原型进行包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆