js对象类型
1 getOwnPropertyDescriptor
var o, d;
o = { get foo() { return 17; } };
d = Object.getOwnPropertyDescriptor(o, "foo");
// d is { configurable: true, enumerable: true, get: /*访问器函数*/, set: undefined }
o = { bar: 42 };
d = Object.getOwnPropertyDescriptor(o, "bar");
// d is { configurable: true, enumerable: true, value: 42, writable: true } o = {};
Object.defineProperty(o, "baz", { value: 8675309, writable: false, enumerable: false });
d = Object.getOwnPropertyDescriptor(o, "baz");
for(var p in d){
alert(p+"->"+d[p]);
}
// d is { value: 8675309, writable: false, enumerable: false, configurable: false }
2 getOwnpropertyNames
// var arr = ["a", "b", "c"];
//alert(Object.getOwnPropertyNames(arr).sort()); // 输出"0,1,2,length"
//
//// 类数组对象
//var obj = { 0: "a", 1: "b", 2: "c"};
//alert(Object.getOwnPropertyNames(obj).sort()); // 输出"0,1,2"
//
//// 使用Array.forEach输出属性名和属性值
//Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
//alert(val + " -> " + obj[val]);
//});
//// 输出
//// 0 -> a
//// 1 -> b
//// 2 -> c
//
////不可枚举属性
//var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; }, enumerable: false } });
//my_obj.foo = 1;
//
//alert(Object.getOwnPropertyNames(my_obj).sort()); // 输出"foo, getFoo" //下面的例子演示了该方法不会获取到原型链上的属性:
function ParentClass() {}
ParentClass.prototype.inheritedMethod = function () {};
function ChildClass() {
this.prop = 5;
this.method = function () {};
}
ChildClass.prototype = new ParentClass;
ChildClass.prototype.prototypeMethod = function () {};
alert(Object.getOwnPropertyNames(new ChildClass())); //弹出["prop", "method"]))
3 getPrototypeOf
var proto={};
var obj=Object.create(proto);
alert(Object.getPrototypeOf(obj)===proto);
alert(Object.getPrototypeOf(obj));
4 hasOwnProperty
//使用 hasOwnProperty 方法判断某对象是否含有特定的自身属性
var o=new Object();
o.prop='exits';
function changeO(){
o.newprop=o.prop;
delete o.prop;
}
// alert(o.hasOwnProperty('prop'));
// changeO();
// alert(o.hasOwnProperty('prop'));
//自身属性和继承属性的区别
//o = new Object();
//o.prop = 'exists';
//alert(o.hasOwnProperty('prop')); // 返回 true
//alert(o.hasOwnProperty('toString')); // 返回 false
//alert(o.hasOwnProperty('hasOwnProperty')); // 返回 false
//遍历一个对象的所有自身属性
//何在遍历一个对象的所有属性时忽略掉继承属性,注意这里 for..in 循环只会遍历可枚举属性,这通常就是我们想要的,
//直接使用 Object.getOwnPropertyNames() 方法也可以实现类似的需求。
var buz = {
fog: 'stack'
};
for (var name in buz) {
if (buz.hasOwnProperty(name)) {
alert("this is fog ("+ name + ") for sure. Value: "+ buz[name]); }
else {
alert(name); // toString or something else
}
}
//hasOwnProperty 方法有可能被遮蔽
//如果一个对象拥有自己的 hasOwnProperty 方法, 则原型链上的同名方法会被遮蔽(shadowed)
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // 始终返回 false
// 如果担心这种情况,可以直接使用原型链上真正的 hasOwnProperty 方法
alert(({}).hasOwnProperty.call(foo, 'bar')); // true
alert(Object.prototype.hasOwnProperty.call(foo, 'bar')); // true
5 isExtenstion
// 新对象默认是可扩展的.
var empty = {};
alert(Object.isExtensible(empty) === true);
// ...可以变的不可扩展.
Object.preventExtensions(empty);
alert(Object.isExtensible(empty) === false);
// 密封对象是不可扩展的.
var sealed = Object.seal({});
alert(Object.isExtensible(sealed) === false);
// 冻结对象也是不可扩展.
var frozen = Object.freeze({});
alert(Object.isExtensible(frozen) === false);
6 isFrozen
// 一个对象默认是可扩展的,所以它也是非冻结的.
alert(Object.isFrozen({}) === false);
// 一个不可扩展的空对象同时也是一个冻结对象.
var vacuouslyFrozen = Object.preventExtensions({}); alert(Object.isFrozen(vacuouslyFrozen) === true); // 一个非空对象默认也是非冻结的.
var oneProp = { p: 42 };
alert(Object.isFrozen(oneProp) === false);
// 让这个对象变的不可扩展,并不意味着这个对象变成了冻结对象,
// 因为p属性仍然是可以配置的(而且可写的).
Object.preventExtensions(oneProp);
alert(Object.isFrozen(oneProp) === false);
// ...如果删除了这个属性,则它会成为一个冻结对象.
delete oneProp.p;
alert(Object.isFrozen(oneProp) === true);
// 一个不可扩展的对象,拥有一个不可写但可配置的属性,则它仍然是非冻结的.
var nonWritable = { e: "plep"};
Object.preventExtensions(nonWritable);
Object.defineProperty(nonWritable, "e", { writable: false }); // 变得不可写alert(Object.isFrozen(nonWritable) === false);
// 把这个属性改为不可配置,会让这个对象成为冻结对象.
Object.defineProperty(nonWritable, "e", { configurable: false }); // 变得不可配置
alert(Object.isFrozen(nonWritable) === true);
// 一个不可扩展的对象,拥有一个不可配置但可写的属性,则它仍然是非冻结的.
var nonConfigurable = { release: "the kraken!"};
Object.preventExtensions(nonConfigurable);
Object.defineProperty(nonConfigurable, "release", { configurable: false }); alert(Object.isFrozen(nonConfigurable) === false);
// 把这个属性改为不可写,会让这个对象成为冻结对象.
Object.defineProperty(nonConfigurable, "release", { writable: false }); alert(Object.isFrozen(nonConfigurable) === true);
// 一个不可扩展的对象,值拥有一个访问器属性,则它仍然是非冻结的.
var accessor = { get food() { return "yum"; } };
Object.preventExtensions(accessor);
alert(Object.isFrozen(accessor) === false);
// ...但把这个属性改为不可配置,会让这个对象成为冻结对象.
Object.defineProperty(accessor, "food", { configurable: false });
alert(Object.isFrozen(accessor) === true);
// 使用Object.freeze是冻结一个对象最方便的方法.
var frozen = { 1: 81 };
alert(Object.isFrozen(frozen) === false);
Object.freeze(frozen);
alert(Object.isFrozen(frozen) === true);
// 一个冻结对象也是一个密封对象.
alert(Object.isSealed(frozen) === true);
// 当然,更是一个不可扩展的对象.
alert(Object.isExtensible(frozen) === false);
7 isProtype
function Fee() {
// . . .
}
function Fi() {
// . . .
}
Fi.prototype = new Fee();
function Fo() {
// . . .
}
Fo.prototype = new Fi();
function Fum() {
// . . .
}
Fum.prototype = new Fo();
var fum = new Fum();
if(Fi.prototype.isPrototypeOf(fum)){
alert('this is a test');
}
8 isSealed
// 新建的对象默认不是密封的.
var empty = {};
alert(Object.isSealed(empty) === false);
// 如果你把一个空对象变的不可扩展,则它同时也会变成个密封对象.
Object.preventExtensions(empty);
alert(Object.isSealed(empty) === true);
// 但如果这个对象不是空对象,则它不会变成密封对象,因为密封对象的所有自身属性必须是
不可配置的.
var hasProp = { fee: "fie foe fum"};
Object.preventExtensions(hasProp);
alert(Object.isSealed(hasProp) === false);
// 如果把这个属性变的不可配置,则这个对象也就成了密封对象.
Object.defineProperty(hasProp, "fee", { configurable: false });
alert(Object.isSealed(hasProp) === true);
// 最简单的方法来生成一个密封对象,当然是使用Object.seal.
var sealed = {};
Object.seal(sealed);
alert(Object.isSealed(sealed) === true);
// 一个密封对象同时也是不可扩展的.
alert(Object.isExtensible(sealed) === false);
// 一个密封对象也可以是一个冻结对象,但不是必须的.
alert(Object.isFrozen(sealed) === true); // 所有的属性都是不可写
var s2 = Object.seal({ p: 3 });
alert(Object.isFrozen(s2) === false); // 属性"p"可写
var s3 = Object.seal({ get p() { return 0; } });
alert(Object.isFrozen(s3) === true); // 访问器属性不考虑可写不可写,只考虑是否可配置
9 keys
var arr = ["a", "b", "c"];
alert(Object.keys(arr)); // 弹出"0,1,2"
// 类数组对象
var obj = {
0: "a",
1: "b",
2: "c"
};
alert(Object.keys(obj)); // 弹出"0,1,2"
// getFoo是个不可枚举的属性
var my_obj = Object.create({}, {
getFoo: {
value: function() {
return this.foo
}
}
});
my_obj.foo = 1;
alert(Object.keys(my_obj)); // 只弹出foo
10 Number
var n=new Number(123.456);
document.write(n.toFixed(2));
document.write("
");
document.write(n.valueOf());
document.write("
");
// alert(Number.isInteger(123));
// alert(Number.isFinite(123));
// alert(Number.isInteger(3.1));
document.write(n.toExponential(2));
document.write("
");
document.write(n.toPrecision(4));
// alert(Number.NaN);
document.write("
");
document.write(Number.MAX_VALUE);
document.write("
");
document.write(Number.MIN_VALUE);
document.write('
');
document.write(Number.POSITIVE_INFINITY);
document.write("
");
document.write(Number.NEGATIVE_INFINITY);
document.write('
');
document.write(Number.MAX_VALUE);
document.write("
");
document.write(Number.prototype);
document.write("
");
document.write(n.valueOf());
document.write("
");
document.write(n.toString());
11 创建新对象
//通过new Object()创建对象
var obj=new Object();
// https://www.360docs.net/doc/d62825643.html,='king';
// var username=https://www.360docs.net/doc/d62825643.html,;
//// alert(username);
//// alert(typeof(obj));
////通过对象字面量创建对象
// var obj1={};
// obj1['name']='queen';
// var username1=obj1['name'];
// alert(username+'--'+username1);
// alert(typeof(obj1));
// obj.break='aaa';
// var test=obj.break;
// alert(test);
// obj['for']='this is for';
// alert(obj['for']);
// alert(obj);
// document.write(obj);
var person={
username:'king',
age:12,
sex:'男',
salary:12345.678,
married:true,
details:{
addr:'北京',
company:'程序员'
},
say:function(){
alert(this.salary);
alert(https://www.360docs.net/doc/d62825643.html,ername);
alert('this is king show time');
}
};
// alert(https://www.360docs.net/doc/d62825643.html,ername);
//// delete https://www.360docs.net/doc/d62825643.html,ername;
// delete person['username'];
// alert(https://www.360docs.net/doc/d62825643.html,ername);
// alert(person.details.addr);
// person.say();
// alert(person['username']);
// alert(person['details']['company']);
person.say();
delete person.say;
person.say();
12 属性
function Person(name,age,sex){
https://www.360docs.net/doc/d62825643.html,=name;
this.age=age;
this.sex=sex;
https://www.360docs.net/doc/d62825643.html,erInfo=function(){
return '用户名:'+https://www.360docs.net/doc/d62825643.html,+'
性别:'+this.sex+'
年龄:'+age+'
';
}
}
// var person1=new Person('king',12,'男');
// var test=person1;
//// test.age=100;
//// alert(test.age);
//// alert(person1.age);
// var obj={num1:1};
// var func=function(o){o.num1=3};
// func(obj);
// alert(obj.num1);
//// alert(https://www.360docs.net/doc/d62825643.html,);
//// alert(https://www.360docs.net/doc/d62825643.html,erInfo());
// document.write(https://www.360docs.net/doc/d62825643.html,erInfo());
// document.write("
");
// var person2=Person('queen',34,'女');
//// alert(typeof person2);
//// alert(typeof https://www.360docs.net/doc/d62825643.html,);
//
// alert(https://www.360docs.net/doc/d62825643.html,);
// alert(typeof person1.constructor);
// var person3=new person1.constructor('张三',34,'保密'); // alert(https://www.360docs.net/doc/d62825643.html,);
// var obj1={};
//// alert(obj1.constructor);
// alert(typeof obj1.constructor);
var obj1={name:'king'};
var obj2={name:'king'};
//alert(obj1==obj2);
var obj3=obj1;
alert(obj1===obj3);
13 object.create
var o;
o=Object.create(null);//创建了一个原型为null的空对象
o={};
o=Object.create(Object.prototype);
o=Object.create(Object.prototype,{
name:{
writable:true,
configurable:true,
value:'king'
},
secert:{
configurable:false,
get: function(){return 'this is a secret'},
set: function(value){document.write("Setting secert is"+value)} }
});
//alert(https://www.360docs.net/doc/d62825643.html,);
//https://www.360docs.net/doc/d62825643.html,='queen';
//alert(https://www.360docs.net/doc/d62825643.html,);
//alert(o.secert);
//o.secert='aaa';
//alert(o.secert);
//var obj={};
14 preventExtension
// Object.preventExtensions将原对象变的不可扩展,并且返回原对象.
var obj = {};
var obj2 = Object.preventExtensions(obj);
alert(obj === obj2);
// 字面量方式定义的对象默认是可扩展的.
var empty = {};
alert(Object.isExtensible(empty) === true);
// ...但可以改变.
Object.preventExtensions(empty);
alert(Object.isExtensible(empty) === false);
// 使用Object.defineProperty方法为一个不可扩展的对象添加新属性会抛出异常.
var nonExtensible = { removable: true };
Object.preventExtensions(nonExtensible);
//Object.defineProperty(nonExtensible, "new", { value: 8675309 }); // 抛出TypeError异常
// 在严格模式中,为一个不可扩展对象的新属性赋值会抛出TypeError异常.
function fail()
{
"use strict";
//nonExtensible.newProperty = "FAIL"; // throws a TypeError
}
fail();
// 一个不可扩展对象的原型是不可更改的,__proto__是个非标准魔法属性,可以更改一个对象的原型.
var fixed = Object.preventExtensions({});
fixed.__proto__ = { oh: "hai"}; // 抛出TypeError异常
15 property
var person={
name:'king'
};
16 propertyIsEnumerable
//propertyIsEnumerable方法的基本用法
var o={};
var a=[];
o.prop='我是可枚举的属性';
a[0]='我也是可枚举的属性';
//alert(o.propertyIsEnumerable('prop'));
//alert(a.propertyIsEnumerable(0));
//用户自定义对象和引擎内置对象
var a = ['我是个可枚举属性'];
a.propertyIsEnumerable(0); // 返回true
a.propertyIsEnumerable('length'); // 返回false
Math.propertyIsEnumerable('random'); // 返回false
this.propertyIsEnumerable('Math'); // 返回false
//自身属性和继承属性
var a = [];
a.propertyIsEnumerable('constructor'); // 返回false,constructor不是自身属性
function firstConstructor() {
this.property = 'is not enumerable';
}
firstConstructor.prototype.firstMethod = function () {};
function secondConstructor() {
this.method = function method() { return 'is enumerable'; };
}
secondConstructor.prototype = new firstConstructor;
secondConstructor.prototype.constructor = secondConstructor;
var o = new secondConstructor();
o.arbitraryProperty = 'is enumerable';
o.propertyIsEnumerable('arbitraryProperty'); // 返回true
o.propertyIsEnumerable('method'); // 返回true
o.propertyIsEnumerable('property'); // 返回false,property是继承属性
o.property = 'is enumerable';
o.propertyIsEnumerable('property'); // 返回true
// 继承属性都返回false
o.propertyIsEnumerable('prototype'); // 返回false
o.propertyIsEnumerable('constructor'); // 返回false
o.propertyIsEnumerable('firstMethod'); // 返回false
17 seal
var obj = {
prop: function () {},
foo: "bar"
};
// 可以添加新的属性,已有属性的值可以修改,可以删除
obj.foo = "baz";
obj.lumpy = "woof";
delete obj.prop;
var o = Object.seal(obj);
alert(o === obj);
alert(Object.isSealed(obj) === true);
// 仍然可以修改密封对象上的属性的值.
obj.foo = "quux";
alert(obj.foo);
// 但你不能把一个数据属性重定义成访问器属性.
//Object.defineProperty(obj, "foo", { get: function() { return "g"; } }); // 抛出TypeError异常
// 现在,任何属性值以外的修改操作都会失败.
obj.quaxxor = "the friendly duck"; // 静默失败,新属性没有成功添加
delete obj.foo; // 静默失败,属性没有删除成功
// ...在严格模式中,会抛出TypeError异常
function fail() {
"use strict";
//delete obj.foo; // 抛出TypeError异常
//obj.sparky = "arf"; // 抛出TypeError异常
}
fail();
// 使用Object.defineProperty方法同样会抛出异常
//Object.defineProperty(obj, "ohai", { value: 17 }); // 抛出TypeError异常
//Object.defineProperty(obj, "foo", { value: "eit" }); // 抛出TypeError异常
18 toString
//覆盖(遮蔽)默认的toString方法
//可以自定义个方法来取代默认的 toString() 方法。该 toString() 方法不能传入参数并且必须返回一个字符串。
//自定义的 toString() 方法可以是任何我们需要的值
function Dog(name,breed,color,sex) {
https://www.360docs.net/doc/d62825643.html,=name;
this.breed=breed;
this.color=color;
this.sex=sex;
}
theDog = new Dog("Gabby","Lab","chocolate","female");
//alert(theDog.toString());
Dog.prototype.toString = function() {
var ret = "Dog "+ https://www.360docs.net/doc/d62825643.html, + " is a "+ this.sex + " "+ this.color + " "+ this.breed;
return ret;
}
//alert(theDog.toString());
//使用toString()方法来检测对象类型
/*
可以通过toString() 来获取每个对象的类型。
为了每个对象都能通过 Object.prototype.toString() 来检测,
需要以 Function.prototype.call()
或者 Function.prototype.apply() 的形式来调用,把需要检测的对象作为第一个参数传入。 */
var toString = Object.prototype.toString;
alert(toString.call(new Date)); // [object Date]
alert(toString.call(new String)); // [object String]
alert(toString.call(Math)); // [object Math]
//Since JavaScript 1.8.5
alert(toString.call(undefined)); // [object Undefined]
alert(toString.call(null)); // [object Null]