学习js权威指南第四站 ---- 对象

1.通过原型继创建一个新对象 Object.create()

   function inherit(p){
       if(p == null) throw TypeError();
       if(Object.create){
           return Object.create(p);
       }
       var t = typeof p;
       if(t !== 'object' || t !== 'function') throw TypeError();
       function f() {};
       f.prototype = p;
       return new f();
   }
   var obj = {name: 'zhangsan',age: 4};
   var obj2 = inherit(obj);
   obj2.name = 'lisi';
   console.log(obj.name);  //zhangsan obj内的内容并没有改变
   obj2.sex = '男';
   console.log(obj.sex);  //undefined obj内的内容并没有改变
   delete obj2.name;    //这段代码无效,因为name是继承过来的

2.检测属性

  JavaScript中可以通过in运算符、hasOwnProperty()和propertyIsEnumerable()方法完成这个检测属性。

3.属性描述

  通过调用Object.getOwnPropertyDescriptor()可以获得某个对象特定的属的属性描述符。

console.log(Object.getOwnPropertyDescriptor(obj,'name'))
//输出:value: "zhangsan", writable: true, enumerable: true, configurable: true console.log(Object.getOwnPropertyDescriptor(obj2,'name'))  //输出:undefined,由此看出,getOwnPropertyDescriptor()只能得到自有的属性描述,不能得到继承的

  想要设置或者修改属性的某种特性 则需要调用Object.defineProperty().多个则使用defineProperties().

  Object.defineProperty(obj2,'id',{value:1,writable: true, enumerable: true, configurable: true});
   Object.defineProperty(obj2,'id',{writable: false});
   obj2.id = 3;  //修改无效
   Object.defineProperty(obj2,'id',{value: 4});  //修改生效

4.isPrototypeOf()

  想要检测一个对象是否是另一个对象的原型(或处于原型链中),可以使用isPrototypeOf()方法。

5.classof()

  通过Object.prototype.toString.call() 自定义一个函数calssof来判断类型。

        function classof(o){
            if(o === null) return null;
            if(o === undefined) return undefined;
            return Object.prototype.toString.call(o).slice(8,-1)
        }
        console.log(classof(null));
        console.log(classof(1));
        console.log(classof(""));
        console.log(classof(false));
        console.log(classof({}));
        console.log(classof([]));
        console.log(classof(/./));
        console.log(classof(new Date()));
        console.log(classof(window));
        function g() {};
        console.log(classof(inherit));
        console.log(classof(new g()));

6.可扩展性

  通过传入Object.esExtensible()来判断对象是否可扩展,也可以通过Object.prevenExtensions()转换成不可扩展。可扩展性的目的是将对象‘锁定’,以避免外界干扰。

7.序列化对象

  对象序列化是指将对象的状态转换成字符串,也可以将字符串还原为对象。

  var s = JSON.stringify(obj);  //对象转字符串
  var p = JSON.parse(s);      //字符串转对象   

8.对象方法

  ①toString()

  ②toLocaleString()  可转换Date

  ③toJSON()

  ④valueOf()      可将Date转换成时间戳

猜你喜欢

转载自www.cnblogs.com/zhongxy/p/9135874.html