/*
字面量和构造函数
当以new操作符调用构造函数时,含税内部将发生:
创建一个空对象并且this变量引用了该对象,同时还继承了该函数的原型
属性和方法被jiarudaothis引用的对象中
新创建的对象由this所引用,并且最后隐式地返回this
构造函数的返回值
默认是this所引用的对象,如果不向this添加任何属性,则返回的是“空对象”,这个空对象继承了构造函数的原型
强制使用new的模式
在构造函数中检查this是否为构造函数的一个实例,如果为否,构造函数可以再次调用自身
*/
/*自调用构造函数*/
function Constructor() {
if (!(this instanceof Constructor)) {
return new Constructor();
}
//init
this.message = "Created";
}
console.log(Constructor().message);
console.log(new Constructor().message);
// 输出:
// Created
// Created
/*
使用arguments.callee进行比较来判定
由于严格模式不支持arguments.callee,所以应当限制使用
*/
function Constructor_callee() {
if (!(this instanceof arguments.callee)) {
return new Constructor_callee();
}
//init
this.message = "Created(callee)";
}
console.log(Constructor_callee().message);
console.log(new Constructor_callee().message);
// 输出:
// Created(callee)
// Created(callee)
/*
数组字面量
一个数组仅仅是一个零值索引列
检查数组性质
typeof返回‘object’
ECMAScript 5定义了一个Array.isArray()来判断是不是数组
如果无法使用新方法,使用Object.prototype.toString.call(myArray) === "[object Array]"来判定
*/
console.log(Array.isArray([]));
console.log(Object.prototype.toString.call([]) === "[object Array]");
// 输出:
// true
// true
/*
JSON
JSON字符串中,不能使用正则表达式字面量
仅当属性名称不是有效的标识符时才需要引号
使用JSON.parse()方法解析字符串
使用JSON.stringfy()方法序列化生成字符串
*/
var obj4Json = {
jsonArray: [1, 2, 3],
jsonObj: {
name: "pro_name",
address: "bupt"
},
jsonStr: "pro_string",
jsonNumber: 2345,
jsonBool: false
},
jsonStr = JSON.stringify(obj4Json);
console.log(jsonStr);
console.log(JSON.parse(jsonStr));
// 输出:
// {"jsonArray":[1,2,3],"jsonObj":{"name":"pro_name","address":"bupt"},"jsonStr":"pro_string","jsonNumber":2345,"jsonBool":false}
// Object {jsonArray: Array[3], jsonObj: Object, jsonStr: "pro_string", jsonNumber: 2345, jsonBool: false}
/*
正则表达式字面量
优先使用字面量创建正则表达式
基本值类型包装器
使用new Number()、new String()、new Boolean()创建包装对象,typeof为object
一般使用基本类型,只有需要扩充属性的时候才使用包装类型
如果没有使用new操作符,包装器构造函数返回的将是基本类型
*/
console.log(typeof (new Number(22)));
console.log(typeof (new String("asdf")));
console.log(typeof (new Boolean(false)));
// 输出:
// object
// object
// object
console.log(typeof (Number(22)));
console.log(typeof (String("asdf")));
console.log(typeof (Boolean(false)));
// 输出:
// number
// string
// boolean
var base_str = "string";
var obj_str = new String("string");
base_str.property = 1;
obj_str.property = 1;
console.log(base_str.property);
console.log(obj_str.property);
// 输出:
// undefined
// 1
// 分析:
// 给基本类型添加属性时,并不会报错,只是忽略
// 给包装类型添加属性可以正常工作,因为它们是object
/*
错误对象
JS内置的错误对象构造函数有
Error(),SyntaxError(),TypeError()
它们都有如下属性
name:构造函数呃名称属性
message:创建时传递给构造函数的字符串
错误的行号和文件名:额外属性,浏览器扩展属性,不可靠
throw适用于任何对象
错误构造函数不带new时与带new行为一样
*/
try{
(function(){
throw 404;
})();
}catch(e){
console.log(e);
}
try{
(function(){
throw "Error";
})();
}catch(e){
console.log(e);
}
try{
(function(){
throw {
name : "MyError",
message : "This is an error"
};
})();
}catch(e){
console.log(e);
}
// 输出:
// 404
// Error
// This is an error
《JavaScript模式》--第三章:字面量和构造函数
最新推荐文章于 2019-07-15 10:05:30 发布