复习:
以下类型都是 object
console.log(typeof new Object);
console.log(typeof new Array());
console.log(typeof new Date());
console.log(typeof new RegExp());
console.log(typeof new String());
console.log(typeof new Number());
console.log(typeof new Boolean());
console.log(typeof Math); // 就是一个对象 不能new
// 函数的类型是 function
console.log(typeof new Function());//function
typeof 6种类型 number string boolean undefined object function
in 运算符
作用:判断指定的属性是否存在于被检测的对象中(含自身属性和原型属性,无论普通 / 不可枚举 / 原型)
语法: key in obj
var obj = {
"name": "chuanchuan",
"age": 19,
"gender": "male"
};
// 遍历对象
for(var k in obj) {
console.log("key = " + k + ", v = " + obj[k]);//这里不能写obj.k;
}
console.log("age" in obj);// true
console.log("toString" in obj); // true toString 是继承来的
var arr = [1, 0];
// 对数组来说,索引就是数组的属性
console.log(2 in arr); // false 0和1在 2就不在了
// 判断是否存在属性的方法:
// 1 in
// var obj = {};
// console.log("age" in obj);
// 2 if
if(obj.age) {
// 如果有 。。。。
} else {
// 没有。。。
}
面试题
// 判断两个对象是否相等
console.log({
} === {
}); // false
console.log({
} == {
}); // false
console.log("1" == 1); // true
console.log("1" === 1); // false
// 值类型(简单类型)
// 如果存储的是数据本身,那么就是值类型5种
// 包括:string / number /boolean / null / undefined
// 引用类型(复杂类型)
// 如果存储的是数据的引用(地址),那么就是引用类型9种
// 包括:Object Function Array Date Math RegExp String Number Boolean
1. 为对象定义方法的两种方式
Product.prototype.buy=function(){
};
Product.prototype={
buy:function(){
}
}
2. 用构造函数创建属性的四种方式
/*传参形式*/
function Product(name){
this.name = name
}
Product.prototype={
}
var iphone = new Product('iphone8s')
/*默认值*/
function Product(){
this.name = ''
this.price=0
}
Product.prototype={
}
var iphone = new Product()
/*动态添加形式*/
iphone.description='XXXXXXXXXX'
iphone.images=[]
/*混合模式*/
function Product(name,price){
this.name = name
this.price=price
this.version=1.0
this.add=function(){
}
}
Product.prototype={
}
3. instanceof; A instanceof B 检测构造函数B的原型属性在不在A的原型链上
4. 两个面试题
①
var fun1 = function(){
this.name = 'peter';
return {
name: 'jack'
};
}
var p1 = new fun1();
console.log(p1.name)// jack
②
var fun2 = function(){
this.name = 'peter';
return 'jack';
}
var p2 = new fun2();
console.log(p2.name)//peter
③
var o = new Object();