JS学习笔记02-初识原型

<!DOCTYPE HTML>
<html lang="en">
<head>
 <meta charset="UTF-8"> 
    <title>test</title>
    <style type="text/css">    
    </style>
    </head>
    
<body>
     <script type="text/javascript">
        //◆ 所有对象都继承自Object.prototype,它在原型链中是最后一个。     
        Object.prototype.age = 1;
        var obj1 = {};
        console.log(obj1.age);        
        if ('age' in obj1){        
           console.log(obj1.hasOwnProperty('age'));//验证是否来自本地对象
        }
/* ◆ 每个function都具有prototype属性,对象都有隐式的__proto__。 ◆ 通过function实例化的对象,对象本身的__proto__指向function的prototype。 ◆ 对象本身的constructor指向function。 */ function f(){ this.age=2; } debugger; var obj2 = new f(); console.log(obj2.__proto__===f.prototype);//true 对象本身的__proto__指向function的prototype console.log(obj2.__proto__.__proto__===f.prototype.__proto__? f.prototype.__proto__===Object.prototype:'false');//true console.log(obj2.constructor===f);//true //对象本身的constructor指向function console.log(f.prototype.isPrototypeOf(obj2));//true 检测obj2是否是f生成的对象

//分解上面new创建的过程 var obj3 = {}; //创建一个空对象 obj3.__proto__===Object.prototype obj3.__proto__=f.prototype; //使对象__proto__指向__prototype f.call(obj3); //将f的this替换成obj3,然后再调用f函数. console.log(obj3.__proto__===f.prototype);// true console.log(obj3.constructor===f);// true </script> </body>

 

posted @ 2014-06-01 15:30  fuyunlong  阅读(109)  评论(0编辑  收藏  举报