Javascript对象初探

【前言】

这篇文章:http://blog.csdn.net/uikoo9/article/details/38752635,介绍了一做的一个js插件,

但是问题有很多,其中一个就是一些参数是写死的,使得定制不是很方便。

这里抽点时间看下javascript的对象,然后对这个插件做一个改进。


【创建对象】

javascript的创建对象有多种方法,下面一一考虑。


【方法一】

function Person(name, age, job){
	this.name = name;
	this.age = age;
	this.job = job;
	this.sayName = function(){
		alert(this.name);
	};
}

var person1 = new Person('test',12,'coder');

缺点:每次new对象的时候都会创建一个sayName,内存浪费,若将sayName函数提取出来又不能称作封装了。


【方法二】

function Person(){}
Person.prototype = {
	constructor : Person,
	name : 'test',
	age : 12,
	job : 'coder',
	sayName : function(){
		alert(this.name);
	}
};
var person1 = new Person();

缺点:对象创建方法必须初始化参数,若参数中有引用类型就会有问题

ps:

1.string的startWiths最简单的实现方法:

	String.prototype.startWith=function(s){  
	    return this.indexOf(text) == 0;
	};

2.判断一个属性是存在于实例中还是对象原型中

function hasPrototypeProperty(object, name){
	return !object.hasOwnProperty(name) && (name in object);
}

3.方法一和方法二的结合,前者用来定义属性,后者用来定义方法

function Person(name,age,job){
	this.name = name;
	this.age = age;
	this.job = job;
	this.friends = ['test','test1'];
}
Person.prototype = {
	constructor : Person,
	sayName : function(){
		alert(this.name);
	}
};

【方法三】

function Person(name,age,job){
	// 属性
	this.name = name;
	this.age = age;
	this.job = job;
	this.friends = ['test','test1'];
	
	// 方法
	if(typeof this.sayName != 'function'){
		Person.prototype.sayName = function(){
			alert(this.name);
		};
	}
}

这个方法已经是很完美的了,推荐使用。


【方法四】

function Person(name,age,job){
	var o = new Object();
	o.name = name;
	o.age = age;
	o.job = job;
	o.sayName = function(){
		alert(this.name);
	};
	return o;
}


你可能感兴趣的:(Javascript对象初探)