构造函数:通过new操作符调用的函数就是构造函数
创建对象的三种方式:
1:变量直接量(JSON格式key:value)
var obj1={ name:‘xxx‘, age:‘xxx‘, sad:function(){} }
2:通过new Object()方式
var obj2=new Object(); obj2.name=‘xxx‘; obj2.age=20; obj2.say=function(){}
3:通过构造函数的方式,优点:可以当做模板
//构造函数Dog() function Dog(){ this.name=‘xxxx‘; this.age=10; this.sad=function(){console.log(this.age)} } var dog1=new Dog(); dog1.age=20; dog1.sad();//20 //1 new操作符 :的内部原理 1:创建一个空对象 2:把this指向到这个空对象 3:把空对象的内部原型指向构造函数的原型对象 4:当前构造函数执行完成后,如果没有return的话,就会把当前的空对象返回,一般都没有return //1 new操作符原理:执行的时候类似在构造函数Dog()内部,过程可以如下去理解,实际不是!! function Dog(){ var tt={}; this=tt; tt.__proto__=Dog.prototype; this.name=‘xxxx‘; this.age=10; this.sad=function(){...} return tt; } //prototype只有函数才有的原型 //__proto__所有的对象都有的 dog1.__proto__===Dog.prototype;//true dog1.prototype===Dog.prototype;//false
3.1上面的升级版本
function Dog(usename,age){ this.name=usename; this.age=age; this.sad=function(){console.log(this.age)} } Dog.prototype.speak=function(){ console.log(‘I am ‘+this.name+‘ ‘+‘今年 :‘+this.age); } var dog1=new Dog(‘dog1‘,20); var dog2=new Dog(‘dog2‘,100); dog1.sad(); dog2.sad(); dog1.speak(); dog2.speak();
3.2 上面的再升级版本
function Dog(option){ this.name=option.name; this.age=option.age; this.sad=function(){console.log(this.age)} } Dog.prototype.speak=function(){ console.log(‘I am ‘+this.name+‘ ‘+‘今年 :‘+this.age); } var dog1=new Dog({name:‘dog1‘,age:20}); var dog2=new Dog({name:‘dog2‘,age:100}); dog1.sad(); dog2.sad(); dog1.speak(); dog2.speak();
3.3 还可以再次升级
function Dog(option){ this.init(option); } //重新设定原型 Dog.prototype={ init:function(option){ this.age=option.age||‘‘; this.name=option.name||‘‘; this.sad=function(){ console.log(this.age); } }, speak:function(){ console.log(‘I am ‘+this.name+‘ ‘+‘今年 :‘+this.age); } } var dog1=new Dog({name:‘dog1‘,age:20}); var dog2=new Dog({name:‘dog2‘,age:100}); dog1.sad(); dog2.sad(); dog1.speak(); dog2.speak();
原文:http://www.cnblogs.com/-walker/p/6287357.html