构造函数
a. 构造函数的首字母大写 (习惯)
b. 内部使用this对象,指向即将生成的实例对象
c. 使用new来生成实例对象
new 一个对象
| 12
 3
 4
 5
 6
 7
 
 | function Person(){this.p = “I’m in constructed object”;
 this.alertP = function(){
 alert(this.p);
 }
 }
 var o2 = new Person();
 
 | 
new操作符来调用一个函数,发生了什么?
| 12
 3
 4
 
 | var obj = {}obj._ptoto_ = Person.prototype;
 Person.call(obj);
 return obj
 
 | 
prototype属性 
每一个构造函数都有一个属性:prototype,其作用是为一个特定类申明通用的变量和函数。
在函数内定义的变量和函数如果不对外提供接口,外部将无法访问。
| 12
 3
 4
 5
 
 | function Obj(){var a=0; //私有变量
 var fn=function(){ //私有函数
 }
 }
 
 | 
| 12
 3
 
 | var o=new Obj();console.log(o.a); //undefined
 console.log(o.fn); //undefined
 
 | 
静态变量、函数
当定义一个函数后,通过.添加的属性和函数,通过对象本身是可以访问,但实例却不可以访问,这样的变量和函数称为静态变量和静态函数。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | function Obj(){
 }
 
 Obj.a=0; //静态变量
 
 Obj.fn=function(){ //静态函数
 
 }
 
 console.log(Obj.a); //0
 console.log(typeof Obj.fn); //function
 
 var o=new Obj();
 console.log(o.a); //undefined
 console.log(typeof o.fn); //undefined
 
 | 
实例变量和函数
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | function Obj(){this.a=[]; //实例变量
 this.fn=function(){
 //实例方法
 }
 }
 
 console.log(typeof Obj.a); //undefined
 console.log(typeof Obj.fn); //undefined
 
 var o=new Obj();
 console.log(typeof o.a); //object
 console.log(typeof o.fn); //function
 
 | 
一个函数要作为一个真正意义上的构造函数,必须满足下列条件:
| 12
 
 | 在函数内部对新对象(this)的属性进行设置,通常是添加属性和方法。构造函数可以包含返回语句(不推荐),但返回值必须是this,或者其它非对象类型的值。
 
 | 
原型和原型链
所有引用类型(函数,数组,对象)都拥有proto属性(隐式原型)
所有函数拥有prototype属性(显式原型)(仅限函数)
原型对象:拥有prototype属性的对象,在定义函数时就被创建
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 
 | //创建构造函数function Word(words){
 this.words = words;
 }
 Word.prototype = {
 alert(){
 alert(this.words);
 }
 }
 //创建实例
 var w = new Word("hello world");
 w.print = function(){
 console.log(this.words);
 console.log(this);  //Person对象
 }
 w.print();  //hello world
 w.alert();  //hello world
 
 | 
实例w的隐式原型指向它构造函数的显式原型,指向的意思是恒等于
| 1
 | w.__proto__ === Word.prototype
 | 
当调用某种方法或查找某种属性时,首先会在自身调用和查找,如果自身并没有该属性或方法,则会去它的proto属性中调用查找,也就是它构造函数的prototype中调用查找。
| 12
 3
 4
 5
 6
 7
 8
 
 | Function.prototype.a = "a";Object.prototype.b = "b";
 function Person(){}
 console.log(Person);    //function Person()
 let p = new Person();
 console.log(p);         //Person {} 对象
 console.log(p.a);       //undefined
 console.log(p.b);       //b
 
 | 
| 12
 3
 4
 5
 6
 7
 
 | function Function(){}console.log(Function); // Function()
 console.log(Function.prototype.constructor);    //Function()
 console.log(Function.prototype.__proto__);      //Object.prototype
 console.log(Function.prototype.__proto__.__proto__);    //NULL
 console.log(Function.prototype.__proto__.constructor);  //Object()
 console.log(Function.prototype.__proto__ === Object.prototype); //true
 
 | 
Live beautifully, dream passionately, love completely