对象
对象是什么
对象是包含相关属性和方法的集合体
什么是面向对象
*面向对象仅仅是一个概念或者编程思想
*通过一种叫做原型的方式来实现面向对象编程
创建对象
1.自定义对象:
*基于Object对象的方式创建对象
语法:var 对象名称 = new Objecct( ); (通过 . 添加属性和方法)
示例:var flower=new Object();
flower.name="长春花";
flower.genera="夹竹桃科 长春花属";
flower.area="非洲、亚热带、热带以及中国大陆的华东、西南、中南等地";
flower.uses="观赏或用药等";
flower.showName=function(){ alert(this.name); }
flower.showName();
*使用字面量赋值方式创建对象
示例:var flower={
name:"长春花",
genera:"夹竹桃科 长春花属",
area:"非洲、亚热带、热带以及中国大陆的华东、西南、中南等地",
uses:"观赏或用药等",
showName:function(){ alert(this.name); }
}
flower.showName();
*内置对象
*常见的内置对象:
String(字符串)对象
Date(日期)对象
Array(数组)对象
Boolean(逻辑)对象
Math(算数)对象
RegExp对象
*String(字符串)对象
length属性
indexOf( )方法、replace( )方法
*Date(日期)对象
getxxx:获取年、月、日、时、分、秒等等
setxxx:设置年、月、日、时、分、秒等等
构造函数
构造函数 | ||
创建特定类型的对象 | this变量 | new操作符 |
创造构造函数
//构造函数始终都应该以一个大写字母开头(Flowe)
function Flowe(name,genera,area,uses){
this.name=name;
......
this.showName=function(){
alert(this.name);
}
}
var flower1=new Flower("长春花","夹竹桃科 长春花属","非洲、亚热带、热带以及中国大陆的华东、西南、中南等地","观赏或用药等")
flower1.showName();
使用构造函数创建对象
var flower2=new Flower("牡丹","芍药科 芍药属","中国","观赏、食用或药用");
flower2.showName();
var flower3=new Flower("曼陀罗花","茄科 曼陀罗属","印度、中国北部","观赏或药用");
flower3.showName();
调用构造函数的4个步骤:
创建一个新对象
将构造函数的作用域赋给新对象(this就指向了这个新对象)
执行构造函数中的代码
返回新对象
constructor属性
constructor属性指向Flower
示例:alert(flower1.constructor==Flower);
alert(flower2.constructor==Flower);
alert(flower3.constructor==Flower);
constructor属性存在于原型对象中,他指向了构造函数
<script type="text/javascript">
function Person(){
}
alert(Person.prototype.constructor === Person);//true
var p1= new Person();
//使用instanceof 操作符可以判断一个对象的类型。
//typeof一般用来获取简单类型和函数,而引用类型一般使用instanceof,因为引用类型用typeof总是返回object。
alert(p1 instanceof Person); //true
</script>
根据需要,可以Person.prototype 属性指定新的对象,来作为Person的原型对象。
但是这个时候有个问题,新的对象的constructor属性则不再指向Person构造函数了。
<script type="text/javascript">
function Person(){
}
//直接给Person的原型指定对象字面量,则这个对象的constructor属性不再指向Person函数
Person.prototype ={
name:"志玲",,
age:20
};
var p1 =new Person();
alert(p1.name); //志玲
alert(p1 instanceof Person); //true
alert(Person.prototype.constructor === Person); //false
//如果constructor对你很重要,你应该在Person,pratotype中添加一行这样的代码:
/*
Person.prototype ={
constructor:Person //让constructor重新指向Person函数
}
*/
</script>
instanceo操作符
使用instanceof操作符检测对象类型
alert(flower1 instanceof Object);
alert(flower1 instanceof Flower);
alert(flower2 instanceof Object);
alert(flower2 instanceof Flower);
alert(flower3 instanceof Object);
alert(flower3 instanceof Flower);