原型函数与javascript中的普通函数有何不同? [英] How are prototype functions different than normal functions in javascript ?

查看:67
本文介绍了原型函数与javascript中的普通函数有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在对象原型上声明Javascript函数,如下所示:

Javascript functions can be declared on a objects prototype like this:

<object name>.prototype.<variable name>=function(){
//
//
}

这与下面的声明有何不同?

How it this different than following declaration?

<object name>.<variable name>=function(){
//
//
}

原型如何?函数与javascript中的普通函数不同?

How are prototype functions different than normal functions in javascript ?

推荐答案

在基础对象的原型上声明的函数由该对象类型的所有实例继承。

functions declared on a base object's prototype are inherited by all instances of that object type.

例如..

String.prototype.foo = function () {
  return 'bar';
};

现在,每个字符串都有函数foo()可用。

Now, every string will have the function foo() available.

'test'.foo(); //返回'bar'

阅读有关基于原型的继承的更多信息这里

Read more about prototype-based inheritance here

这篇关于原型函数与javascript中的普通函数有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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