1.內置對象創建 var girl=new Object(); girl.name='hxl'; console.log(typeof girl); 2.工廠模式,寄生構造函數模式 function Person(name){ var p=new Object();//內部進行實例化 p.name=
1.內置對象創建
var girl=new Object(); girl.name='hxl'; console.log(typeof girl);
2.工廠模式,寄生構造函數模式
function Person(name){ var p=new Object();//內部進行實例化 p.name=name; p.say=function(){ console.log('my name is '+ p.name); } return p;//註:一定要返回 } var girl=Person('haoxioli'); girl.say();
3.構造函數創建
var Product=function(name){ this.name=name; this.buy=function(){ console.log('我衣服的牌子是'+this.name); } } var pro=new Product('真維斯'); pro.buy();
4.原型創建,缺點:實例中的每個屬性有可能會不一樣
var Role=function(){} Role.prototype.name={nickName:'昵稱'}; var boy=new Role(); boy.name.nickName='劉曉兵'; console.log(boy.name.nickName);//劉曉兵 var girl=new Role(); girl.name.nickName='郝曉利'; console.log(boy.name.nickName);//郝曉利,因為實例對象可以修改原型中的引用對象的值 console.log(girl.name.nickName);//郝曉利
5.混合模式:原型+構造,可以把不讓實例修改的屬性放到構造函數中,可以修改的放原型中
var Role=function(){ this.name={nickName:'aaa'}; } Role.prototype.age=30; var boy=new Role(); boy.name.nickName='boy'; console.log(boy.name.nickName);//boy var girl=new Role(); girl.name.nickName='girl'; console.log(boy.name.nickName);//boy,實例不會修改構造函數中的值 console.log(girl.name.nickName);//girl
6.字面量形式
var cat={ name:'lucy', age:3, sex:'母' };//將對象轉換成字元串 console.log(JSON.stringify(cat));//{"name":"lucy","age":3,"sex":"母"} var dog='{"name":"john","sex":"公"}'; console.log(JSON.parse(dog).name);//將字元串轉為對象
7.拷貝模式
function extend(tar,source){ for(var i in source){ tar[i]=source[i]; } return tar; } var boy={name:'醉俠客',age:20}; var person=extend({},boy); console.log(person.name);
8.第三方框架
//先引入包 <script src='js/base2.js'></script> //base2框架,Base.extend及constructor都是固定用法 var Animal=Base.extend({ constructor:function(name){ this.name=name; }, say:function(meg){ console.log(this.name+":"+meg); } }); new Animal('lily').say('fish');
另一個第三方框架
<script src='js/simplejavascriptinheritance.js'></script> //simplejavascriptinheritance框架,Class.extend及init都是固定用法 var Person=Class.extend({ init:function(name){ this.name=name; } }); var p=new Person(); p.name='over'; console.log(p.name);