JS 创建对象(常见的几种方法)(2)


function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName= function(){
alert(this.name);
};
var tanya = new Person("tanya","30","female");
var ansel = new Person("ansel","30","male");
tanya.sayName();
ansel.sayName();


实际应用时,不是一成不变的套用某种模式,活学活用。需要共享方法的时候就用原型模式,需要使用副本的时候就用构造模式,还可以结合起来,把所有信息都封装在构造函数中,而通过在构造函数中初始化原型,使得对象保持了同时使用构造函数和原型的优点。

复制代码 代码如下:


function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
if (typeof sayName != "function" ){
Person.prototype.sayName= function(){
alert(this.name);
};
}
}
var tanya = new Person("tanya","30","female");
var ansel = new Person("ansel","30","male");
ansel.sayName = function () {
alert("Hi ansel, how hansome you are!");
}
tanya.sayName();
ansel.sayName();

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjzdzx.html