1、创建对象
自定义对象是使用操作符new
内置对象是一种特殊的数据
使用自定义对象和内置对象添加属性和方法
var flower=new Object();
flower.name="长春花";
flower.user="lhm";
flower.show=function(){
alert(this.user);
}
flower.show();
flower.name="长春花";
flower.user="lhm";
flower.show=function(){
alert(this.user);
}
flower.show();
2、构造函数
可用来创建特定类型的对象。
使用构造函数创建新实例,必须使用new操作符,使用构造函数会有四个步骤:
创建一个对象
将构造函数的作用域给新对象
执行构造函数中的代码
返回新对象
将构造函数的作用域给新对象
执行构造函数中的代码
返回新对象
instanceof 可以用来实例标识为一种特定的类型,
<script type="text/javascript">
function Pet() {
this.type=1;
}
this.type=1;
}
Pet.prototype.getType = function () {
return this.type;
}
return this.type;
}
function man() {
this.head=2;
}
man.prototype=new Pet();
man.prototype.getHead = function () {
return this.head;
}
var man1=new man();
alert(man1.getType());
alert(man1.getHead());
alert(man1 instanceof Pet);
alert(man1 instanceof Object);
alert(man1 instanceof man);
this.head=2;
}
man.prototype=new Pet();
man.prototype.getHead = function () {
return this.head;
}
var man1=new man();
alert(man1.getType());
alert(man1.getHead());
alert(man1 instanceof Pet);
alert(man1 instanceof Object);
alert(man1 instanceof man);
3、原形对象
prototype是指一个指针,指向一个对象,
这个对象的用途就是包含可以由特定类型的所有实例共享的属性和方法。
让所有对象共享所有的属性和方法,不用再在函数中定义函数对象实例的信息。
prototype是指一个指针,指向一个对象,
这个对象的用途就是包含可以由特定类型的所有实例共享的属性和方法。
让所有对象共享所有的属性和方法,不用再在函数中定义函数对象实例的信息。
script type="text/javascript">
function Humans(name) {
this.name=name;
this.clothing=["trousers","dress","jacket"];
}
Humans.prototype.sayName=function () {
alert(this.name);
}
function Man(name,age) {
Humans.call(this,name);
this.age=age;
}
Man.prototype=new Humans();
Man.prototype.sayAge=function () {
alert(this.age);
}
var man1=new Man("coat",18);
man1.clothing.push("coat");
alert(man1.clothing);
man1.sayName();
man1.sayAge();
var man2=new Man("tom",20);
alert(man2.clothing);
man2.sayName();
man2.sayAge();
</script>
4、对象继承
原型属性和方法都能实例共享。
借用函数:
在子;类型构造函数的内部调用父类型构造函数,
借用函数有一个优点:可以在子类型构造函数中向父类构造函数传递参数。
5、组合继承
就是把原型对象和对象继承连在一起使用