对js中原型链的一个困惑

 1 <!DOCTYPE HTML>
 2 <html lang="en-US">
 3 <script type="text/javascript">
 4 window.onload = function () {
 5     Function.prototype.method = function (name,func) {
 6         this.prototype[name] = func;
 7         return this;
 8      };
 9     Number.method('integer', function () {
10         return Math[this < 0 ? 'ceil' : 'floor'](this);
11     });
12 
13     var simple = document.getElementById('simple');
14     var outputInt = (-10/3).integer();
15     simple.innerHTML = outputInt;
16 }
17 </script>
18 <head>
19     <meta charset="UTF-8">
20     <title></title>
21 </head>
22 <body>一些无关紧要的内容
23 <div id="simple">这里应该是一个测试数字</div>
24 </body>
25 </html>

解释一下:

1.Function是一个构造函数,用于创建一个函数对象

2.function是一个关键字,用于声明一个函数对象

3.每一个函数对象都继承 Function 构造函数的原型对象

1 Function.prototype.foo = 1
2 
3 var bar = function () {}
4 bar.foo // 1

4.A是构造函数,a是A的实例 ( 即 a = new A )

那么有:a.constructor = A  实例的构造函数

    a.[[proto]] = A.prototype

    Object.prototype.[[proto]] = null 这是‘金字塔’的顶端的象征

5.Function.prototype.method 在 Function原型上定义了method方法,作用是在调用method方法的对象上添加了‘name’属性

6.this.prototype[name]应该这么看:1、this.prototype;2、[name]

 

 1 Function.prototype.method = function(name,func){
 2     this.prototype[name] = func;
 3     return this;
 4 };
 5 
 6 function Fun(){
 7     
 8 }
 9 
10 var Func = Fun.method('getValue',function(value){
11     return 'this is value:'+value;
12 });
13 
14 print(new Func().getValue(8));//this is value:8
  • Function.prototype.method 在 Function原型上定义了method方法,作用是在调用method方法的对象上添加了‘name’属性
  • 然后我们定义Fun构造函数,Fun.__proto__即 Function.prototype,所以Fun拥有method方法,我们来调用它,得到Func,Func即是拥有name(也就是getValue)方法的构造函数。
  • 然后new一个Func对象出来,调用getValue方法
posted @ 2017-08-17 22:36  vxee  阅读(112)  评论(0编辑  收藏  举报