JS对象的补充

对象构造器

如下面这个对象构造器,和Java的构造方法很像:

function Person(name,age){
    
    
    this.name = name;
    this.age = age;//这里的this代替还没有被创建的对象
}

构造器使用如下,使用又很像Java的对象声明:

var Vincent = new Person('Vincent',18);
console.log(Vincent);//Person {name: "Vincent", age: 18}

这样可以创建相同类型的Person对象。然而为构造器添加新的属性或者方法,只能在代码中添加。
JavaScript还有很多内置的对象构造器:Object(),String(),Number(),Boolean(),Array(),RegExp(),Function(),Date()。Math() 对象不再此列。Math 是全局对象。new 关键词不可用于 Math。
然而在创建对象的时候尽量使用字面量来代替构造器的方式,因为new 关键字使代码复杂化。会拖慢执行速度,也可能产生一些意想不到的结果 详情查看

对象原型

所有的JavaScript对象的属性和方法都继承自它的原型。数组(Array)对象继承自Array.prototype;Vincent对象则是继承自Person.prototype,而这些对象都是继承自Object.prototype。 Object.prototype位于原型继承链的顶端。

Object.prototype
{
    
    constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, 

我们可以利用原型来实现给自定义的构造器添加新属性或新方法:

Person.prototype.nationality = "China";//给Person原型添加新属性nationality
var Vincent = new Person("Vincent",24);
console.log(Vincent.nationality)//"China"

添加方法的方式类似,只修改自己自定义的原型,对于JavaScript内置的一些原型不要修改。

ES5的一些对象方法

Object.defineProperty(object, property, descriptor) :添加或者更改对象的属性(修改已有属性或新建自有属性,不可修改继承属性)

//Object.defineProperty(object, property, {value : value})
Object.defineProperty(Vincent, "gender", {
    
    value : "male"});
Person {
    
    name: "Vincent", age: 24, gender: "male"}

Object.getPrototypeOf(object):访问原型

Object.getPrototypeOf(Vincent);
{
    
    nationality: "China", constructor: ƒ}

还有一些其他方法请点击

如下可以很好的说明:Object.prototype位于原型继承链的顶端。

Object.getPrototypeOf(Person.prototype) == Object.prototype;//true

猜你喜欢

转载自blog.csdn.net/weixin_41481695/article/details/107053232