JavaScript Object使用笔记

1、Object.create(prototype[,propertiesObject]):第一个参数为对象,对象为函数调用之后返回新对象的原型对象,第二个参数为对象本身的实例方法(默认不能修改,不能枚举)

const obj = Object.create({a:1}, {b: {value: 2}});
obj.__proto__.a === 1      // true 
obj.b = 3;
console.log(obj.b)      // 2

2、Object.defineProperty(object, prop, descriptor)

var obj = {};

// 1.添加一个数据属性
Object.defineProperty(obj, "newDataProperty", {
    value: 101,
    writable: true,
    enumerable: true,
    configurable: true
});

// 2.修改数据属性
Object.defineProperty(obj, "newDataProperty", {
    writable:false
});

// 3.劫持访问器属性
Object.defineProperty(obj, "newAccessorProperty", {
    set: function (x) {
        this.otherProperty = x;
    },
    get: function () {
        return this.otherProperty;
    },
    enumerable: true,
    configurable: true
});

3、Boolean hasOwnProperty(key): 对象自身属性中是否具有指定的属性,返回布尔值。

let o = {a: 1 }

o.hasOwnProperty('a')   //true
o.hasOwnProperty('b')   //false   对象自身没有属性b
o.hasOwnProperty('toString');  //false  不能检测对象原型链上的属性

4、getOwnPropertyDescriptor(obj, prop): 返回指定对象上一个自有属性对应的属性描述符。

let obj = { foo: 123 };
Object.getOwnPropertyDescriptor(obj, 'foo')

//  { value: 123, writable: true, enumerable: true, configurable: true }

5、getOwnPropertyDescriptors(obj): 返回指定对象上所有自有属性对应的属性描述符。

const obj = {
  foo: 123,
  get bar() { return 'abc' }
};
 
console.dir(Object.getOwnPropertyDescriptors(obj))
//   { 
//      foo:{ value: 123,
//        writable: true,
//        enumerable: true,
//        configurable: true 
//      },
//      bar:{ 
//        get: [Function: bar],
//        set: undefined,
//        enumerable: true,
//        configurable: true 
//      } 
//   }

6、getPrototypeOf(obj): 获取一个对象的原型在 chrome 中可以通过_proto_的形式,或者在 ES6 中可以通过 Object.getPrototypeOf 的形式。

const prototype1 = {};
const object1 = Object.create(prototype1);

console.log(Object.getPrototypeOf(object1) === prototype1);   // true

// 需要注意的地方
Object.getPrototypeOf(new Object()) === Object.prototype    // true
Object.getPrototypeOf(Object) === Object.prototype    // false
Object.getPrototypeOf(Object) === Function.prototype;  // true

7、is(obj1, obj2): 用来比较两个值是否严格相等,与严格比较运算符(===)的行为基本一致

Object.is('foo', 'foo')     // true
Object.is({}, {})           // false

// ==、===、Object.is之间的区别
+0 === -0                   //true
NaN === NaN                     // false

Object.is(+0, -0)           // false
Object.is(NaN, NaN)         // true

// ==在比较时,会将值强制转换成number、null==undefined
" " == 0              //true 
"0" == 0              //true 
" " != "0"            //true 
123 == "123"            //true 
null == undefined       //true

​​​​​​​

​​​​​​​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值