数据类型
在javascript中,数据类型分为两类:
原始类型:保存一些简单数据,如true,5等。javascript共有5中原始类型:
●boolean:布尔,值为true或false
●number:数字,值为任何整型会浮点数值
●string:字符串,值为由单引号或双引号括出的单个字符或连续字符(javascript不区分字符类型)
●null:空类型,其仅有一个值:nulll
●undefined:未定义,其仅有一个值:undefined
var name = "pomy";
var blog = "http://www.ido321.com";
var age = 22;
alert(typeof blog); //"string"
alert(typeof age); //"number"
原始类型的值是直接保存在变量中,并可以用typeof进行检测。但是typeof对null的检测是返回object,而不是返回null:
//弹出not null
if(typeof null){
alert("not null");
}else{
alert("null");
}
所以检测null时,最好用全等于(===),其还能避免强制类型转换:
console.log("21" === 21); //false
console.log("21" == 21); //true
console.log(undefined == null); //true
console.log(undefined === null); //false
对于字符串、数字或者布尔值,其都有对应的方法,这些方法来自于对应的原始封装类型:string、number和boolean。原始封装类型将被自动创建。
var name = "pomy";
var char = name.charat(0);
console.log(char); //"p"
在javascript引擎中发生的事情:
var name = "pomy";
var temp = new string(name);
var char = temp.charat(0);
temp = null;
console.log(char); //"p"
字符串对象的引用在用完之后立即被销毁,所以不能给字符串添加属性,并且instanceof检测对应类型时均返回false:
var name = "pomy";
name.age = 21;
console.log(name.age); //undefined
console.log(name instanceof string); //false
引用类型:保存为对象,实质是指向内存位置的引用,所以不在变量中保存对象。除了自定义的对象,javascript提供了6中内建类型:
●array:数组类型,以数字为索引的一组值的有序列表
●date:日期和时间类型
●error:运行期错误类型
●function:函数类型
●object:通用对象类型
●regexp:正则表达式类型
可以用new来实例化每一个对象,或者用字面量形式来创建对象:
var obj = new object;
var own = {
name:"pomy",
blog:"http://www.ido321.com",
"my age":22
};
console.log(own.blog); //访问属性
console.log(own["my age"]);
obj = null; //解除引用
obj 并不包含对象实例,而是一个指向内存中实际对象所在位置的指针(或者说引用)。因为typeof对所有非函数的引用类型均返回object,所以需要用instanceof来检测引用类型。
函数
在javascript中,函数就是对象。使函数不同于其他对象的决定性特性是函数存在一个被称为[[call]]的内部属性。内部属性无法通过代码访问而是定义了代码执行时的行为。
创建形式
1、函数声明:用function关键字,会被提升至上下文
2、函数表达式:不能被提升
3、实例化function内建类型
sayhi(); //函数提升
function sayhi(){
console.log("hello");
}
//其他等效等效方式
/*
var sayhi = function(){
console.log("hello");
}
var sayhi = new function(" console.log(\"hello\");");
*/
参数
javascript函数的另外一个独特之处在于可以给函数传递任意数量的参数。函数参数被保存在arguments类数组对象中,其自动存在函数中,能通过数字索引来引用参数,但它不是数组实例:
alert(array.isarray(arguments)); //false
类数组对象arguments 保存的是函数的实参,但并不会忽略形参。因而,arguments.length返回实参列表的长度,arguments.callee.length返回形参列表的长度。
function ref(value){
return value;
}
console.log(ref("hi"));
console.log(ref("hi",22));
console.log(ref.length); //1
函数中的this
关于this的问题,可参考此文:javascript中的this。
javascript提供了三个方法用于改变this的指向:call、apply和bind。三个函数的第一个参数都是指定this的值,其他参数均作为参数传递给函数。
对象
对象是一种引用类型,创建对象常见的两种方式:object构造函数和对象字面量形式:
var per1 = {
name:"pomy",
blog:"http://www.ido321.com"
};
var per2 = new object;
per2.name = "不写代码的码农";
属性操作
在javascript中,可以随时为对象添加属性:
per1.age = 0;
per1.sayname = function(){
alert(this.name); //"pomy"
}
因而,在检测对象属性是否存在时,常犯的一个错误是:
//结果是false
if(per1.age){
alert(true)
}else{
alert(false);
}
per1.age 是存在的,但是其值是0,所以不能满足if条件。if判断中的值是一个对象、非空字符串、非零数字或true时,判断会评估为真;而当值是一个null、undefined、0、false、nan或空字符串时评估为假。
因而,检测属性是否存在时,有另外的两种方式:in和hasownproperty(),前者会检测原型属性和自有(实例)属性,后者只检测自有(实例)属性。
console.log("age" in per1); //true
console.log(per1.hasownproperty("age")); //true
console.log("tostring" in per1); //true
console.log(per1.hasownproperty("tostring")); //false
对象per1并没有定义tostring,该属性继承于object.prototype,所以in和hasownproperty()检测该属性时出现差异。如果只想判断一个对象属性是不是原型,可以利用如下方法:
function isprototypeproperty(obj,name){
return name in obj && !obj.hasownproperty(name);
}
若要删除一个属性,用delete操作符,用于删除自有属性,不能删除原型属性。
per1.tostring = function(){
console.log("per1对象");
};
console.log(per1.hasownproperty("tostring")); //true
per1.tostring(); //"per1对象"
delete per1.tostring;
console.log(per1.hasownproperty("tostring")); //false
console.log(per1.tostring()); //[object object]
有时需要枚举对象的可枚举属性,也有两种方式:for-in循环和object.keys(),前者依旧会遍历出原型属性,后者只返回自有属性。所有可枚举属性的内部属性[[enumerable]]的值均为true。
var per3 = {
name:"pomy",
blog:"http://www.ido321.com",
age:22,
getage:function(){
return this.age;
}
};
实际上,大部分原生属性的[[enumerable]]的值均为false,即该属性不能枚举。可以通过propertyisenumerable()检测属性是否可以枚举:
console.log(per3.propertyisenumerable("name")); //true
var pros = object.keys(per3); //返回可枚举属性的名字数组
console.log("length" in pros); //true
console.log(pros.propertyisenumerable("length")); //false
属性name是自定义的,可枚举;属性length是array.prototype的内建属性,不可枚举。
属性类型
属性有两种类型:数据属性和访问器属性。二者均具有四个属性特征:
●数据属性:[[enumerable]]、[[configurable]]、[[value]]和[[writable]]
●访问器属性:[[enumerable]]、[[configurable]]、[[get]]和[[set]]
[[enumerable]]:布尔值,属性是否可枚举,自定义属性默认是true。 [[configurable]]:布尔值,属性是否可配置(可修改或可删除),自定义属性默认是true。它是不可逆的,即设置成false后,再设置成true会报错。
[[value]]:保存属性的值。
[[writable]]:布尔值,属性是否可写,所有属性默认可写。
[[get]]:获取属性值。
[[set]]:设置属性值。
es 5提供了两个方法用于设置这些内部属性:
object.defineproperty(obj,pro,desc_map) 和 object.defineproperties(obj,pro_map)。利用这两个方法为per3添加一个属性和创建一个新对象per4:
object.defineproperty(per3,"sex",{
value:"male",
enumerable:false,
configurable:false, //属性不能删除和修改,该值也不能被设置成true
});
console.log(per3.sex); //'male'
console.log(per3.propertyisenumerable("sex")); //false
delete per3.sex; //不能删除
per3.sex = "female"; //不能修改
console.log(per3.sex); //'male'
object.defineproperty(per3,"sex",{
configurable:true, //报错
});
per4 = {};
object.defineproperties(per4,{
name:{
value:"dwqs",
writable:true
},
blog:{
value:"http://blog.92fenxiang.com"
},
name:{
get:function(){
return this.name;
},
set:function(value){
this.name = value;
},
enumerable:true,
configurable:true
}
});
console.log(per4.name); //dwqs
per4.name = "pomy";
console.log(per4.name); //pomy
需要注意的是,通过这两种方式来定义新属性时,如果不指定特征值,则默认是false,也不能创建同时具有数据特征和访问器特征的属性。可以通过object.getownpropertydescriptor()方法来获取属性特征的描述,接受两个参数:对象和属性名。若属性存在,则返回属性描述对象。
var desc = object.getownpropertydescriptor(per4,"name");
console.log(desc.enumerable); //false
console.log(desc.configurable); //false
console.log(desc.writable); //true
根据属性的属性类型,返回的属性描述对象包含其对应的四个属性特征。
禁止修改对象
对象和属性一样具有指导其行为的内部特征。其中,[[extensible]]是一个布尔值,指明改对象本身是否可以被修改([[extensible]]值为true)。创建的对象默认都是可以扩展的,可以随时添加新的属性。
es5提供了三种方式:
●object.preventextensions(obj):创建不可扩展的obj对象,可以利用object.isextensible(obj)来检测obj是否可以扩展。严格模式下给不扩展对象添加属性会报错,非严格模式下则添加失败。
●object.seal(obj):封印对象,此时obj的属性变成只读,不能添加、改变或删除属性(所有属性都不可配置),其[[extensible]]值为false,[[configurable]]值为false。可以利用object.issealed(obj)来检测obj是否被封印。
●object.freeze(obj):冻结对象,不能在冻结对象上添加或删除属性,不能改变属性类型,也不能写入任何数据类型。可以利用object.isfrozen(obj)来检测obj是否被冻结。
注意:冻结对象和封印对象均要在严格模式下使用。
"use strict";
var per5 = {
name:"pomy"
};
console.log(object.isextensible(per5)); //true
console.log(object.issealed(per5)); //false
console.log(object.isfrozen(per5)); //false
object.freeze(per5);
console.log(object.isextensible(per5)); //false
console.log(object.issealed(per5)); //true
console.log(object.isfrozen(per5)); //true
per5.name="dwqs";
console.log(per5.name); //"pomy"
per5.hi = function(){
console.log("hi");
};
console.log("hi" in per5); //false
delete per5.name;
console.log(per5.name); //"pomy"
var desc = object.getownpropertydescriptor(per5,"name");
console.log(desc.configurable); //false
console.log(desc.writable); //false
注意,禁止修改对象的三个方法只对对象的自有属性有效,对原型对象的属性无效,仍然可以在原型上添加或修改属性。
function person(name){
this.name = name;
}
var person1 = new person("pomy");
var person2 = new person("dwqs");
object.freeze(person1);
person.prototype.hi = function(){
console.log("hi");
};
person1.hi(); //"hi";
person2.hi(); //"hi";
构造函数和原型对象
构造函数也是函数,用new创建对象时调用的函数,与普通函数的一个区别是,其首字母应该大写。但如果将构造函数当作普通函数调用(缺少new关键字),则应该注意this指向的问题。
var name = "pomy";
function per(){
console.log("hello "+this.name);
}
var per1 = new per(); //"hello undefined"
var per2 = per(); //"hello pomy"
使用new时,会自动创建this对象,其类型为构造函数类型,指向对象实例;缺少new关键字,this指向全局对象。
可以用instanceof来检测对象类型,同时每个对象在创建时都自动拥有一个constructor属性,指向其构造函数(字面量形式或object构造函数创建的对象,指向object,自定义构造函数创建的对象则指向它的构造函数)。
console.log(per1 instanceof per); //true
console.log(per1.constructor === per); //true
每个对象实例都有一个内部属性:[[prototype]],其指向该对象的原型对象。构造函数本身也具有prototype属性指向原型对象。所有创建的对象都共享该原型对象的属性和方法。
function person(){}
person.prototype.name="dwqs";
person.prototype.age=20;
person.prototype.sayname=function()
{
alert(this.name);
};
var per1 = new person();
per1.sayname(); //dwqs
var per2 = new person();
per2.sayname(); //dwqs
alert(per1.sayname == per2.sayname); //true
所以,**实例中的指针仅指向原型,而不指向构造函数。**es5提供了hasownproperty()和ispropertyof()方法来反应原型对象和实例之间的关系
alert(person.prototype.isprototypeof(per2)); //true
per1.blog = "www.ido321.com";
alert(per1.hasownproperty("blog")); //true
alert(person.prototype.hasownproperty("blog")); //false
alert(per1.hasownproperty("name")); //false
alert(person.prototype.hasownproperty("name")); //true
因为原型对象的constructor属性是指向构造函数本身,所以在重写原型时,需要注意constructor属性的指向问题。
function hello(name){
this.name = name;
}
//重写原型
hello.prototype = {
sayhi:function(){
console.log(this.name);
}
};
var hi = new hello("pomy");
console.log(hi instanceof hello); //true
console.log(hi.constructor === hello); //false
console.log(hi.constructor === object); //true
使用对象字面量形式改写原型对象改变了构造函数的属性,因此constructor指向object,而不是hello。如果constructor指向很重要,则需要在改写原型对象时手动重置其constructor属性
hello.prototype = {
constructor:hello,
sayhi:function(){
console.log(this.name);
}
};
console.log(hi.constructor === hello); //true
console.log(hi.constructor === object); //false
利用原型对象的特性,我们可以很方便的在javascript的内建原型对象上添加自定义方法:
array.prototype.sum=function(){
return this.reduce(function(prev,cur){
return prev+cur;
});
};
var num = [1,2,3,4,5,6];
var res = num.sum();
console.log(res); //21
string.prototype.capit = function(){
return this.charat(0).touppercase()+this.substring(1);
};
var msg = "hello world";
console.log(msg.capit()); //"hello world"
继承
利用[[prototype]]特性,可以实现原型继承;对于字面量形式的对象,会隐式指定object.prototype为其[[prototype]],也可以通过object.create()显示指定,其接受两个参数:第一个是[[prototype]]指向的对象(原型对象),第二个是可选的属性描述符对象。
var book = {
title:"这是书名";
};
//和下面的方式一样
var book = object.create(object.prototype,{
title:{
configurable:true,
enumerable:true,
value:"这是书名",
wratable:true
}
});
字面量对象会默认继承自object,更有趣的用法是,在自定义对象之间实现继承。
var book1 = {
title:"js高级程序设计",
gettitle:function(){
console.log(this.title);
}
};
var book2 = object.create(book1,{
title:{
configurable:true,
enumerable:true,
value:"js权威指南",
wratable:true
}
});
book1.gettitle(); //"js高级程序设计"
book2.gettitle(); //"js权威指南"
console.log(book1.hasownproperty("gettitle")); //true
console.log(book1.isprototypeof("book2")); //false
console.log(book2.hasownproperty("gettitle")); //false
当访问book2的gettitle属性时,javascript引擎会执行一个搜索过程:现在book2的自有属性中寻找,找到则使用,若没有找到,则搜索[[prototype]],若没有找到,则继续搜索原型对象的[[prototype]],直到继承链末端。末端通常是object.prototype,其[[prototype]]被设置为null。
实现继承的另外一种方式是利用构造函数。每个函数都具有可写的prototype属性,默认被自懂设置为继承自object.prototype,可以通过改写它来改变原型链。
function rect(length,width){
this.length = length;
this.width = width;
}
rect.prototype.getarea = function(){
return this.width * this.length;
};
rect.prototype.tostring = function(){
return "[rect"+this.length+"*"+this.width+"]";
};
function square(size){
this.length = size;
this.width = size;
}
//修改prototype属性
square.prototype = new rect();
square.prototype.constructor = square;
square.prototype.tostring = function(){
return "[square"+this.length+"*"+this.width+"]";
};
var rect = new rect(5,10);
var square = new square(6);
console.log(rect.getarea()); //50
console.log(square.getarea()); //36
如果要访问父类的tostring(),可以这样做:
square.prototype.tostring = function(){
var text = rect.prototype.tostring.call(this);
return text.replace("rect","square");
}
更多javascript面向对象精要。