标签:app 资源 说明 构造函数 模式 工厂 obj var ***
//如果有new函数里的this就是指的当前创建出来的对象。
//判断某个实例是否属于该对象 instanceof 返回值为true/false
//使用call或apply改变作用域,改变上下文。
1.基本的创建对象
var people = new Object();
people.name=‘张三‘;
people.weapon=‘大刀‘;
//this指的是在当前作用域下的对象,跟谁调用这个方法有关
//或者说该函数是谁调用的,则this就指向谁
people.run = function(){
return this.name+"的武器是"+this.weapon;
}
2.工厂模式创建对象(就是将基本模式进行封装,最后返回该对象)
function createPeople(name,weapon){
var people = new Object();
people.name = name;
people.weapon = weapon;
people.run = function (){
return this.name+"的武器是"+this.weapon;
}
return people;
}
//函数是引用类型,复制时是其地址。
//工厂模式下实例的引用地址却不相等,说明存储地址不一样,因此会引起
//资源浪费。
3.构造函数模式创建对象(本质也是普通的函数,只是使用了new调用,专门用来
生产对象)
function People(name,weapon){
this.name = name;
this.weapon = weapon;
this.run = function(){
return this.name+"的武器是"+this.weapon
}
}
var shaseng = new People(‘沙僧‘,‘禅杖‘);
//缺点未改变实例的内存地址的问题。
4.prototype模式创建对象。
function people(){};
people.prototype.name=‘小兵‘;
people.prototype.weapon=‘短剑‘;
people.prototype.run=function(){
return this.name+"的武器是"+this.weapon
}
var monster = new people();
*************************************************************
上面方法可以更换为(但存在区别:constructor的返回不同,可强制指回constructor:people)
function people(){}
people.prototype={
name:‘小兵‘,
weapon:‘大刀‘,
job:[‘巡山‘,‘打更‘],
run:function(){return this.name+‘的工作 是‘+this.job,
}
}
5.组合模式(构造模式和原型模式)
function people(name,arr){
this.name = name;
this.job = arr;
}
people.prototype= {
run:function(){return this.name+‘的工作是‘+this.job}
}
var peopleA = new people(‘小旋风‘,["巡山","打更","挑水"])
6.动态原型模式(体现封装性,但是注意执行效率)
function people(name,arr){
this.name = name;
this.job = arr;
if (typeof this.run!=‘function‘){
people.prototype.run= function(){
return this.name+‘的工作是‘+this.job
}
}
}
标签:app 资源 说明 构造函数 模式 工厂 obj var ***
原文地址:http://www.cnblogs.com/gouzizhang/p/7483862.html