<script>
//工厂模式:会出现不能查看实体对象是谁的实例化
function CreatObj(name,age){
var obj= new Object()
obj.name= name
obj.age=age
obj.say =function(){
alert(this.name+this.age+"hello")
}
return obj
}
var cat1= CreatObj('cat',6)
var dog= CreatObj('dog',8)
cat1.say()
dog.say()
//构造函数:解决实体是谁的实例化对象
function CreatObj(name,age){
this.name= name
this.age=age
this.say =function(){
alert(this.name+this.age+"hello")
}
}
var cat1= new CreatObj('cat',6)
var dog=new CreatObj('dog',8)
cat1.say()
dog.say()
/*区别:工厂要return ;构造函数自动返回;构造函数首字母要大写*/
// 原型 prototype属性
function Cat(){
}
//原型属性和方法
Cat.prototype.name='tom'
Cat.prototype.age= 2
Cat.prototype.say=function(){
alert(1)
}
var cat1= new Cat()
var dog=new Cat()
cat1.say()
dog.say()
//原型调用的方法是同一个的:值会共享
//完善原型
function Cat(name,age){
this.name=name
this.age=age
}
Cat.prototype.say=function(){
alert(1)
}
var cat1= new Cat('tom',2)
var dog=new Cat('jerry',2)
cat1.say()
dog.say()
//通过字面量创建
function Cat(){
Cat.prototype = {
constructor:Cat, //强制指向cat
name: 'tom',
age: 2,
syahi:function(){
alert(this.name+this.age+"hello")
}
}
}
var cat1= new Cat()
cat1.say()
//通过字面量创建完善
function Cat(name,age){
this.name=name
this.age=age
}
Cat.prototype = {
constructor:Cat, //强制指向cat
syahi:function(){
alert(this.name+this.age+"hello")
}
}
var cat1= new Cat('tom',2)
cat1.say()
//给内置对象增加自己属性
String.prototype.add=function(){
return this+'hehe'
}
alert('a'.add)
</script>
转载请标明出处:js面向对象编程-构建对象
文章来源: js面向对象编程-构建对象