当我们可以添加属性时,为什么要使用原型 [英] Why to use prototype when we can just add a property

查看:92
本文介绍了当我们可以添加属性时,为什么要使用原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个javasctipt类

I have this javasctipt class

function employee(name, jobtitle, born)
{
    this.name = name;
    this.jobtitle = jobtitle;
    this.born = born;
}

var fred = new employee("Fred Flintstone", "Caveman", 1970);
employee.prototype.salary = null;
fred.salary = 20000;
fred.notprototype = 1239;
console.log(fred);

现在您可以看到我使用原型添加了工资属性,但之后我只是使用<添加了一个属性code> fred.notprototype = 1239; 不使用原型。

now as you can see I added salary property using prototype but then I just added a property by using fred.notprototype = 1239; without the use of prototype.

当我在对象fred上执行console.log时,我看到那里没有原型。那么添加原型是不对的吗?如果是,那么它有什么区别呢?

when I did the console.log on object fred I see notprototype there. So Is it wrong not to add the prototype? If it is then what difference is it making?

推荐答案

让我们说,在你完成所有代码后添加这个:

Let's say, after all that code you add this:

var john = new employee("John Carson", "Philantropist", 2015);
console.log(john);

它会显示 john 有一个 salary 属性(值 null )。你没有自己设置它,它来自原型链。

It will show that john has a salary attribute (of value null). You didn't set that yourself, it comes from the prototype chain.

通过添加 X的原型 ,你改变了由 new X()创建的所有对象。

By adding to a prototype of X, you change all objects that are created by new X().

另一个例子:

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

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

var school_one = new School('one');

console.log(school_one.getName()); // prints "one"

在此示例中,方法 getName 已添加到原型中。创建 school_one 对象后,它继承自 School.prototype 您添加到它的所有内容(在这种情况下只是那个方法)。

In this example, a method getName was added to the prototype. Upon creation of the school_one object it inherits from School.prototype all that you have added to it (in this case just that one method).

这可以用来声明对象的接口(用来访问它的方法)或默认值与构造函数分开。

This can be used to declare the object's interface (methods you use to access it) or default values separate from the constructor.

为了更深入地了解JavaScript及其独特功能,我强烈建议您查看一些来自 Douglas Crockford ;他是一个伟大的演讲者,知识渊博,爱听他:)

To get a deeper understanding of JavaScript and its unique features, I highly recommend checking out a few videos from Douglas Crockford; he's a great speaker and highly knowledgeable, love listening to him :)

这篇关于当我们可以添加属性时,为什么要使用原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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