原型的目的是什么? [英] What’s the purpose of prototype?

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

问题描述


可能重复:

了解JavaScript中的原型继承


好的,所以我是对于JS中的OOP的想法有点新。



下面这两段代码的区别是什么:

  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;
}

他们都做同样的事情,那有什么区别?

解决方案

使用原型可以更快地创建对象,因为每次创建新对象时都不必重新创建该函数。 / p>

执行此操作时:

  function animal(){
this.name ='rover';
this.set_name = function(name){
this.name = name;
}
}

set_name 每次创建动物时都会创建 de novo 的功能。但是当你这样做时

  animal.prototype.set_name = function(name){
this.name = name;
}

每次都不需要重新创建该函数;它存在于原型的一个地方。因此,当您调用 someAnimal.set_name(Ubu); 上下文将设置为<$ c $将调用c> someAnimal 和(唯一的) set_name 函数。






使用第一种语法有一个好处:以这种方式创建的函数可以访问私有数据:

  function animal(){
var privateData ='foo'

this.name = 漫游者;
this.set_name = function(name){
this.name = name;
alert(privateData); //将提醒'foo'
}
}

Douglas Crockford调用函数因为这个原因创建了这样的特权:他们可以访问公共和私人数据。


Possible Duplicate:
Understanding prototypal inheritance in JavaScript

OK, So I am somewhat new to the idea of OOP in JS.

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?

解决方案

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. 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"); the this context will be set to someAnimal and (the one and only) set_name function will be called.


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.

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

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