通过“this”函数分配函数之间的区别是什么?与“原型”相比较。 [英] What is the difference between assigning a function via "this" vs. "prototype"?

查看:185
本文介绍了通过“this”函数分配函数之间的区别是什么?与“原型”相比较。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在Javascript中使用原型与this?

我对这两种类型的向函数添加方法感到困惑。让我以一个例子来解释。

I am confused with these two type of adding a method to a function. Let me explain with an example.


var foo = function(){
    this.bar = function(){alert('I am a method')}
}

foo.prototype.baz = function(){alert('I am another method')}

var car = new foo();

现在,我们可以使用baz和bar方法。嗯,但他们之间的区别是什么。

Now at this point we can use baz and bar methods for car. Well, but what is the difference between them. What is the nuance adding a method to function's prototype or it's constructor.

谢谢..

推荐答案

分配给原型的函数将被所有实例共享;

Functions assigned to the prototype will be shared by all instances; functions assigned in the constructor will have a separate function object per instance.

此外,在构造函数中赋值的函数可以使用构造函数的变量和参数。

Also, functions assign in the constructor can use the constructor's variables and parameters.

例如:

var foo = function(param){
    this.bar = function() { alert('I can see a parameter: ' + param); };
}

foo.prototype.baz = function() { alert('I can't see foo's parameters'); };

var car = new foo("Hi there!");
car.bar();

这篇关于通过“this”函数分配函数之间的区别是什么?与“原型”相比较。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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