[JavaScript]ÀàÖ®Èý
Ïê½âjavascriptÀà¼Ì³Ð»úÖƵÄÔÀí
Ä¿Ç° javascriptµÄʵÏּ̳з½Ê½²¢²»ÊÇͨ¹ý“extend”¹Ø¼ü×ÖÀ´ÊµÏֵģ¬¶øÊÇͨ¹ýconstructor functionºÍprototypeÊôÐÔÀ´ÊµÏּ̳С£Ê×ÏÈÎÒÃÇ´´½¨Ò»¸öanimalÀà
js ´úÂë
var animal = function(){ //Õâ¾ÍÊÇconstructor function ÁË
this.name = 'pipi';
this.age = 10;
this.height = 0;
}
//½¨Á¢Ò»¸ö¶¯ÎïµÄʵÀý
var a1 = new animal ();
¹¹Ô캯ÊýÓëÆäËûÆÕͨº¯ÊýÇø±ðÔÚÓÚ£¬1.¹¹Ô캯ÊýÀïÓÐ this¹Ø¼ü×Ö£¬2.µ÷Óù¹Ô캯ÊýÊÇʹÓõÄnew¹Ø¼ü×Ö¡£Í¨¹ýnewÔËËã·ûµ÷Óù¹Ô캯Êýanimal ºó£¬ÏµÍ³¾Í»á·µ»ØÒ»¸ö¶ÔÏó£¬Õâ¸ö¶ÔÏó¾ÍÏ൱ÓÚ
µÈͬÕâÑùµÄ·½Ê½À´²úÉújs¶ÔÏó¡£
µ½ÕâÀïÎÒÃÇÖªµÀÈçºÎÔÚjsÖж¨ÒåÒ»¸öÀàÁË£¬½ÓÏÂÀ´ÎÒÃÇչʾÈçºÎдһ¸öcat
js ´úÂë
var a1 = { name:'pipi' ,age:10,height:0 }
//»òÕß
var a1 = new Object();
a1.name='pipi';
a1.age = 10;
a1.height = 0;
js ´úÂë
var cat = function(){
this.play = function(){
alert('cat play')
}
}
cat .prototype = new animal ();
//prototype ÊôÐÔÖ¸ÏòÒ»¸ö¶ÔÏó
var c1 = new cat();
µ½ÕâÀcat¾Í¼Ì³ÐÁËanimal ¶ÔÏó£¬ÀàcatµÄÒ»¸öʵÀý¶ÔÏóc1ÓµÓÐÊôÐÔname,age,height,ºÍ·½·¨playÁË¡£
ÄÇôprototypeÆðµ½ÁËÒ»¸öʲôÑùµÄ×÷ÓÃÄØ£¿
prototype¾ÍºÃ±ÈÒ»¸öÖ¸Õ룬ËüÖ¸ÏòÒ»¸öobject£¬Õâ¸öobject¾Í³ÆΪ×ÓÀà¶ÔÏóµÄÔÐÍ¡£µ±catµÄ¶ÔÏó±»´´½¨µÄʱºò£¬ÓÉÓÚcatµÄ¹¹Ô캯ÊýÓµÓÐprototypeÊôÐÔ£¬ÄÇôcatµÄʵÀý¾Í»á¼ä½ÓÖ¸ÏòÕâ¸öÔÐͶÔ
Ïà¹ØÎĵµ£º
1¡¢¶ÔÏóµÄ¼Ì³Ð£¬Ò»°ãµÄ×ö·¨ÊǸ´ÖÆ£ºObject.extend
prototype.jsµÄʵÏÖ·½Ê½ÊÇ£º
Object.extend = function(destination, source){
for (property in source) {
destination[property] = source[property];
}
return destination;
......
¶þÊ®¡¢Bookmarklet
1¡¢Ê²Ã´ÊÇBookmarklet£¿£¨What's a Bookmarklet?£©
Q£ºÊ²Ã´ÊÇBookmarklet£¿
A£ºBookmarkletÊÇÕû¸ö¶¼±»°üº¬ÔÚ³¬Á´½ÓURLÖеÄһС¶ÎJavaScript³ÌÐò¡££¨JavaScript URL¾ÍÊÇÕâ¸öÑù×Ó£º<a href="javascript:the code goes here">¡££©¶àÊýä¯ÀÀÆ÷ÔÊÐíÓû§Ìí¼ÓÕâЩJavaScript URLÊéÇ©£¬¾ÍÏñÌí¼ÓÆäËû³¬Á´½ ......
¶¨ÒåÓëÓ÷¨
The prototype property allows you to add properties and methods to an
object.
prototypeÊôÐÔÔÊÐíÄãÏòÒ»¸ö¶ÔÏóÌí¼ÓÊôÐԺͷ½·¨
Syntax
Óï·¨
object.prototype.name=value
Example 1
ʵÀý
In this example we will show how to use the prototype property to add a
property to an object:
ÔÚÏÂ ......
Ê×ÏÈ¿´demo´úÂ룺
var student={
name:"leo",
intro:function(){
alert("my name is "+this.name);
}
}
var teacher=function(f){
f();
}
teacher(student.intro);
ÔÚÉÏÃæµÄdemo£¬¿ÉÒÔ¿´µ½ÏÔʽµÄ¶¨ÒåÁËÒ»¸ö¶ÔÏóstudent£¬ÓÐÒ»¸ö³ÉÔ±º¯ÊýintroºÍÒ»¸ö³ÉÔ±±äÁ¿¡£
ÁíÍⶨÒåÁËÒ»¸öº¯Êýteacher£¬½ÓÊ ......