将一个函数直接分配给构造函数和它的原型有什么区别?为什么? [英] What is the difference between assigning a function directly to a constructor versus to it's prototype, and why?

查看:158
本文介绍了将一个函数直接分配给构造函数和它的原型有什么区别?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果关闭,请不要使用我的术语。我不明白之间的区别:

Excuse my terminology if it's off. I don't understand the difference between:

function Person() {};
Person.walk = function() {};

和...

function Person() {};
Person.prototype.walk = function() {};

似乎第二种方式是构造函数的约定,但是我不明白差别,为什么会这样做。

It seems that the second way is the convention for constructors, but I don't understand the difference and why it is done that way. Thanks!

推荐答案

第一种情况:

function Person() {};
Person.walk = function() {};

您只能使用以下函数调用函数:

You will be able to call the function only with:

Person.walk();

如果您创建一个Person实例,您将无法调用该方法: p>

If you create an instance of Person, you won't be able to call the method:

p = new Person();
p.walk() // -> TypeError: Object #<Person>  has no method 'walk'

另一方面,如果你使用原型,你将只能通过实例调用方法。

In the other hand, if you use the prototype you will only be able to call the method through an instance.

这篇关于将一个函数直接分配给构造函数和它的原型有什么区别?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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