js面向对象编程-构建对象

           <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 >
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值