JavaScript中原型的含义 [英] Meaning of prototype in javascript

查看:40
本文介绍了JavaScript中原型的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了从 Person 继承 reader 的简短代码:

 < script>/*班级人员.*/函数Person(name){this.name =名称;}Person.prototype.getName = function(){返回this.name;}var reader = new Person('John Smith');alert(reader.getName());</script> 

或者,我可以删除 Person.prototype.getName = function(){} 并在Person对象中创建它.例如

 < script>/*班级人员.*/函数Person(name){this.name =名称;this.getName = function(){返回this.name;}}var reader = new Person('John Smith');alert(reader.getName());</script> 

在这两种情况下,调用 getName()时,我得到的结果都是相同的.那么它们有什么不同?

解决方案

在原型上放置东西时,对象的每个实例与该对象共享相同的代码方法.它们都使用相同的函数实例.

当您简单地在 this 上放置一个方法时,每个对象实例都具有自己的相同方法的副本.

使用 prototype 效率更高.请注意,这就是为什么通常将方法放在原型上的原因,因为您通常希望所有实例都使用相同的方法,而将属性放在实例本身上,因为通常您不希望所有实例都共享相同的属性.

对于您的评论,如果在对象的构造函数上放置一个方法,则实际上已经创建了一个静态"方法.该对象的任何实例都不会具有该方法,它们都必须在构造函数上对其进行访问.因此,在您的情况下,是 Person.someMethod().

I wrote short code of inheritance of reader from Person:

<script>

/* Class Person. */
function Person(name) {
    this.name = name;
}

Person.prototype.getName = function() {
    return this.name;
}

var reader = new Person('John Smith');
alert(reader.getName());

</script>

Alternatively I can delete the line of Person.prototype.getName = function() { return this.name; } and create it in the Person object. For example

<script>
/* Class Person. */
function Person(name) {
    this.name = name;
    this.getName = function() { return this.name;}
}

var reader = new Person('John Smith');
alert(reader.getName());

</script>

I got the same result when invoking getName() in both these cases. So how are they different?

解决方案

When you put something on the prototype, every instance of the object shares the same code for the method. They are all using the same function instance.

When you simply put a method on this, every object instance has its own copy of the same method.

Using prototype is much more efficient. Note this is why typically methods are placed on the prototype, since you typically want all instances to use the same method, but properties are placed on the instance itself, because typically you don't want all instances to share the same properties.

For your comment, if you put a method on the constructor function of an object, then you have in effect created a "static" method. No instance of the object will have that method, they all must access it on the constructor function. So in your case, Person.someMethod().

这篇关于JavaScript中原型的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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