Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

javascript - 原型的目的是什么? [重复](What’s the purpose of prototype? [duplicate])

Possible Duplicate:(可能重复:)

OK, So I am somewhat new to the idea of OOP in JS.(好的,所以我对JS中的OOP有点陌生。)

What is the difference between these two snippets of code written below:(这两个下面的代码片段有什么区别:) function animal(){ this.name = 'rover'; this.set_name = function(name){ this.name = name; } } function animal(){ this.name = 'rover'; } animal.prototype.set_name = function(name){ this.name = name; } They both do the same thing, so what's the difference?(他们俩都做同一件事,所以有什么区别呢?)   ask by Quinton Pike translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using the prototype makes for faster object creation, since that function does not have to be re-created each time a new object is created.(使用原型可以更快地创建对象,因为不必在每次创建新对象时都重新创建该功能。)

When you do this:(执行此操作时:) function animal(){ this.name = 'rover'; this.set_name = function(name){ this.name = name; } } The set_name function is created de novo each and every time you create an animal.(每次创建动物时,都会从头创建set_name函数。) But when you do this(但是当你这样做) animal.prototype.set_name = function(name){ this.name = name; } The function does not have to be re-created each time;(不必每次都重新创建该函数;) it exists in one place in the prototype.(它存在于原型中的一个地方。) So when you call someAnimal.set_name("Ubu");(因此,当您调用someAnimal.set_name("Ubu");) the this context will be set to someAnimal and (the one and only) set_name function will be called.(this上下文将被设置为someAnimal ,并且将调用(唯一的) set_name函数。) There is one advantage to using the first syntax though: functions created in this manner will have access to private data:(但是,使用第一种语法有一个优点:以这种方式创建的函数将可以访问私有数据:) function animal(){ var privateData = 'foo' this.name = 'rover'; this.set_name = function(name){ this.name = name; alert(privateData); //will alert 'foo' } } Douglas Crockford calls functions created like this "privileged" for that reason: they have access to both public, and private data.(出于这个原因,Douglas Crockford将这样创建的函数称为“特权”:它们可以访问公共数据和私有数据。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...