如何写一个js对象构造函数,首先得明白prototype和new这两个是什么意思,做啥的。prototype 属性使你有能力向对象添加属性和方法;而new是创建object + this指向object + __proto__指向,具体的解释可以点开网页看。
<script>
var Test = function () {
//私有属性
var prititle;
//这里还可以加上点其他方法或者变量,因为用立即函数封装,test方法只能内部使用,即Test方法内可以使用,但外部无法使用,即var aaa=new Test(data);aaa.test()调用不到。
//这么做的目的是因为某些属性和方法是暴露供外部使用,某些属性和方法是不暴露,只供内部使用,简而言之就是private和public的识别
function prialert() {//私有方法
alert("私有方法"+prititle);
}
//构造函数
function test(title) {//由于执行new Test("哈哈"),相当执行test("哈哈")
//给私有属性赋值
prititle = title;
//给公有属性赋值
this.pubtitle=title;//this指向test(),由于函数最后return test,所以也可说指向于Test
}
//公有方法
test.prototype.pubalert = function () {
//内部方法可以调用私有属性或这私有方法
alert("私有属性"+prititle);
prialert();
};
//返回构造函数
return test;//相当于test()=Test();
}();//js要实现private和public就是通过立即执行函数(闭包)实现的
var aaa=new Test("哈哈");
aaa.pubalert(); //公用方法,可调用
alert(aaa.prititle);//私有属性,调用不到
aaa.prialert();//私有方法,调用不到
</script>
var Person = (function(window) {
var Person = function(name) {
return new Person.fn.init(name);//new个对象初始化
}
Person.fn = Person.prototype = {
constructor: Person,
init: function(name) {
this.name = name;
this.sayHello = function() {
this.makeArray();//this指向init函数,相当于init.makeArray();
}
},
makeArray: function() {
console.log(this.name);
}
}
/*虽然把makeArray 等常用方法挂载到 Person.prorotype 下面,但还是会被 init 这个实例使用.
执行这行代码后,init.prototype就会具有makeArray的方法,int就可以调用makeArray方法,否则就会报错.
大家可以试着去掉Person.fn.init.prototype = Person.fn代码看看会怎么样
*/
Person.fn.init.prototype = Person.fn;
return Person;
})();//闭包函数
var p = Person('pawn');//无需 new
console.log(p);//返回int()对象
p.sayHello();//执行int.sayHello()