【前言】
这篇文章: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');
【方法二】
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; };
function hasPrototypeProperty(object, name){ return !object.hasOwnProperty(name) && (name in object); }
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; }