JavaScript Prototype (原型鏈) 小記


事緣剛上線後不久..
就和網友討論到JavaScript的Prototype(原型鏈),
在討論中大家都寫了一小點的代碼來討論一些事情,
所以記錄一下相關的實現方法,
兩個版本都參考了jQuery的實現,感覺奇技淫巧

這是朋友在解決問後提供的版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
< !doctype html>
<html lang="zh-tw">
<head></head>
<body>
<p>Attr: [<em id="attr" title="huge, gigantic">large</em>].</p>
</body>
<script>
(function(){

window.$=function(c,o){
console.log(this.init?'>> Init':'>> New Class');
return this.init?this.init(c,o):new $(c,o);
};

$.fn=$.prototype={
init:function(c){
console.log('init');
this[0]=document.getElementById(/^[^< ]*(<(.|\s)+>)[^>]*$|^#(\w+)$/.exec(c)[3]);
return this;
},
html:function(c){
console.log('html');
return this[0].innerHTML;
}
};
})();

alert($('#attr').html());
alert($('#attr').html());
</script>
</html>

之後是我修改和重寫後的faker版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
< !doctype html>
<html lang="zh-tw">
<head>
</head>
<body>
<p>Attr: [<em id="attr" title="huge, gigantic">large</em>].</p>
<p>Attr: [<em id="attr2" title="huge, gigantic">large2</em>].</p>
</body>
<script>
var faker = (function(){
var faker = function(id) {
console.log('New Class');
return new faker.fn.init(id);
};

faker.fn = faker.prototype ={
init: function(id) {
console.log('init');
this.fakerObject = window.document.getElementById(id);
return this;
},

html:function() {
console.log('html');
return this.fakerObject.innerHTML;
}
};

faker.fn.init.prototype = faker.fn;

return window.faker = window.$ = faker;
})();

console.log("第一次"); alert(faker('attr').html());
console.log("第二次"); alert(faker('attr2').html());
</script>
</html>