最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How are prototype functions different than normal functions in javascript ?- Stack Overflow

programmeradmin1浏览0评论

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(){
//
//
}

How are prototype functions different than normal functions in 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(){
//
//
}

How are prototype functions different than normal functions in javascript ?

Share Improve this question edited Jul 18, 2011 at 21:06 ctrlShiftBryan 27.8k26 gold badges75 silver badges78 bronze badges asked Dec 9, 2009 at 3:04 XinusXinus 30.5k34 gold badges122 silver badges168 bronze badges 4
  • 1 Please re-phrase into a real question that can be answered. – gahooa Commented Dec 9, 2009 at 3:10
  • 3 @gahooa: Why do you think this question can't be answered. It might be very high level, but it is still a question. You can always edit it to make it more clear. No need to down vote this simply because of grammatical mistakes... – Josh Commented Dec 9, 2009 at 3:13
  • stackoverflow.com/questions/186244/… – John Paulett Commented Dec 9, 2009 at 3:13
  • Some doggone good stuff here: stackoverflow.com/questions/1595611/… – Crescent Fresh Commented Dec 9, 2009 at 3:17
Add a comment  | 

3 Answers 3

Reset to default 16

Prototype functions are instance functions, whilst normal functions are "static" functions. Functions declared on class's prototype will available on all instances of that class.

var MyClass = function(){
};
MyClass.staticFunction = function(){alert("static");};
MyClass.prototype.protoFunction = function(){alert("instance");};

MyClass.staticFunction(); //OK
MyClass.protoFunction (); //not OK

var myInstance = new MyClass ();
myInstance.staticFunction(); //not OK
myInstance.protoFunction (); //OK

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

For example..

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

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

'test'.foo(); // returns 'bar'

Read more about prototype-based inheritance here

Matt and Igor have already provided enough code samples, but one of the best articles (short, correct and to the point) that you can read is Prototypal Inheritance, by Douglas Crockford.

There are also lots of different ways to facilitate inheritance through popular libraries (Dojo, Prototype, etc)

发布评论

评论列表(0)

  1. 暂无评论