星空网 > 软件开发 > Java

js中一些容易混淆的方法

JavaScript中有一些名字十分冗长的函数名称,导致使用时会混乱,特此整理一番,加深印象。

①Object.getOwnPropertyDescriptor     ——读取某个对象特定属性的属性描述符(value / writable / enumerable / configurable)

这个方法接受两个参数:(属性所在对象  , 要读取其描述符的属性名称),返回值是一个对象。

 

var o = Object.getOwnPropertyDescriptor({x : 1}, 'x');
//{value:1, writable:true, enumerable:true, configurable:true}alert(o); // [object Object]

 

此方法只能取得自身的属性描述符,无法获得继承属性的特性:

var o = Object.getOwnPropertyDescriptor({}, 'toString');
alert(o); //undefined

 

 

 

 ②Object.defineProperty  ——设置某个对象(单个)属性的特性或让新建属性具有某种特性

这个方法接受三个参数:(要修改的对象 , 要创建或修改的属性 、 属性描述符对象)。

 

 var o = {};      Object.defineProperty(o, 'x', {        value : 1,        writable : true,        enumerable : false,        configurable : true      });      alert(o.x);  // 1            Object.defineProperty(o, 'x', {writable : false});      o.x = 2;  //不可行,不会报错,但不会修改, o.x = 1;            Object.defineProperty(o, 'x', {value : 2});      alert(o.x);  // 2     

 

 

③Object.defineProperties  ——  设置某个对象(多个)属性的特性或让新建属性具有某种特性

这个方法接受两个参数:(修改的对象 , 映射表--包含所有新建或者修改属性的名称和属性描述符)。

Object.defineProperties({}, {        _year : {          value : 2016,
            writable : true, 
enumerable : true,
configurable : true }, edition : { value : 1 }, year : { get : function(){ return this._year; }, set : function(newValue){ if(newValue > 2004){ this._year = newValue; this.edition += newValue - 2004; } } } });

以上在一个空对象中定义了两个数据属性(_year和edition),还有一个访问器属性(year),这里额属性都是同一时间创立。

 

④isPrototypeOf  ——确定对象与原型之间存在的关系

function Person(){}            var friend = new Person();      alert(Person.prototype.isPrototypeOf(friend)); //true

因为friend对象内部有一个指向Person.prototype的指针,所以返回true。

 

⑤Object.getPrototypeOf  ——方便地取得一个对象的原型

function Person(){}      Person.prototype.name = 'Tom';            var friend = new Person();      alert(Object.getPrototypeOf(friend) == Person.prototype); // true      alert(Object.getPrototypeOf(friend).name); // Tom

ES5中新增的方法,IE9+支持。

 

⑥hasOwnProperty  ——检测一个属性是存在于实例中,还是存在于原型中

function Person(){}      Person.prototype.name = 'Tom';      Person.prototype.sayName = function(){        alert(this.name);      };            var frient1 = new Person();      frient1.name = 'Jery';      var frient2 = new Person();            alert(frient1.hasOwnProperty('name'));      alert(frient2.hasOwnProperty('name'));

使用hasOwnProperty()可以轻松知晓访问的是实例属性还是原型属性了。

 




原标题:js中一些容易混淆的方法

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流