<!--Function对象 -->
<html>
<head>
<meta charset="utf-8">
<title>Function对象</title>
<script type="text/javascript">
//一.①这个方法不怎么常见
var sum =new Function("x","y","return(x+y)");
//②一般使用第二种
function sum(x,y){
return (x+y);
}
//③函数在JAVAScript有很多功能,他可以看成一个类的申明,函数本身就是一个构造器。列如:
function Cat(name,color){
this.name=name;
this.color=color;
this.eat=function(){alert(this.color+this.name+"吃老鼠")}
}
var cat=new Cat("猫咪","黄色");
cat.eat();
*/
var animal={};
animal.sleep=function(){alert("睡懒觉");};
return animal;
}
};
var Cat={
createNew:function(){
var cat=Animal.createNew();//返回一个Animal对象,存在cat中
cat.name="猫咪";
cat.makeSound=function(){alert("喵喵");};
return cat;
}
};
var cat1=Cat.createNew();
cat1.sleep();
cat1.makeSound();
//2.使用prototype
function Animal1(){
this.sleep=function(){alert("睡觉");};
}
function Dog(){
this.name="小狗";
}
Dog.prototype=new Animal1();//让Dog继承Animal1;
var dog=new Dog();//创建Dog对象
Dog.prototype.type="犬类";//给Dog添加属性
Dog.prototype.newMethod=function(){alert(this.type);}//给dog类添加新的方法
dog.sleep();
dog.newMethod();
alert(dog.name);
</script>
</head>
<body>
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<title>Function对象</title>
<script type="text/javascript">
//一.①这个方法不怎么常见
var sum =new Function("x","y","return(x+y)");
//②一般使用第二种
function sum(x,y){
return (x+y);
}
//③函数在JAVAScript有很多功能,他可以看成一个类的申明,函数本身就是一个构造器。列如:
function Cat(name,color){
this.name=name;
this.color=color;
this.eat=function(){alert(this.color+this.name+"吃老鼠")}
}
var cat=new Cat("猫咪","黄色");
cat.eat();
/*二每一个构造函数都会有一个prototype属性,用于返回对象类型的原型,当它指向另一个对象,
这个对象所有属性和方法,都会被继承。列如*/
var Animal={
createNew: function(){var animal={};
animal.sleep=function(){alert("睡懒觉");};
return animal;
}
};
var Cat={
createNew:function(){
var cat=Animal.createNew();//返回一个Animal对象,存在cat中
cat.name="猫咪";
cat.makeSound=function(){alert("喵喵");};
return cat;
}
};
var cat1=Cat.createNew();
cat1.sleep();
cat1.makeSound();
//2.使用prototype
function Animal1(){
this.sleep=function(){alert("睡觉");};
}
function Dog(){
this.name="小狗";
}
Dog.prototype=new Animal1();//让Dog继承Animal1;
var dog=new Dog();//创建Dog对象
Dog.prototype.type="犬类";//给Dog添加属性
Dog.prototype.newMethod=function(){alert(this.type);}//给dog类添加新的方法
dog.sleep();
dog.newMethod();
alert(dog.name);
</script>
</head>
<body>
</body>
</html>