浅谈JavaScript的面向对象思想(3)


function Person(name,age) {
    this.name = name;
    this._age = age;
    if (typeof Person._getName === "undefined"){
        Person.prototype.getName = function () {
            return this.name;
        };
        Person._getName = true;
    }
 }
var person = new Person("Rose",18);
 Object.defineProperty(person,"age",{
    get:function () {
        return this._age;
    },
    set:function (age) {
        this._age = age;
    }});
person.age = 20;
console.log(person.age);//20//person.age=20是使用set方法将20赋值给_age,person.age是使用get方法将_age的读取出来
console.log(person._age);//20
 

获取所有的属性和属性的特性

使用Object.getOwnPropertyNames(object)方法可以获取所有的属性;

使用Object.getOwnPropertyDescriptor(object,property)方法可以取得给定属性的特性;


function Person(name,age) {
    this.name = name;
    this._age = age;
    if (typeof Person._getName === "undefined"){
        Person.prototype.getName = function () {
            return this.name;
        };
        Person._getName = true;
    }
 }
var person = new Person("Rose",18);
 Object.defineProperty(person,"age",{
    get:function () {
        return this._age;
    },
    set:function (age) {
        this._age = age;
    }});
console.log(Object.getOwnPropertyNames(person));//["name", "_age", "age"]
console.log(Object.getOwnPropertyDescriptor(person,"age"));//{enumerable: false, configurable: false, get: function, set: function}
 

对于数据属性,可以取得:configurable,enumberable,writable和value;

对于访问器属性,可以取得:configurable,enumberable,get和set;

继承机制实现

对象冒充


function Father(name) {
    this.name = name ;
    this.getName = function () {
        return this.name;
    }
 }
function Son(name,age) {
    this._newMethod = Father;
    this._newMethod(name);
    delete  this._newMethod;

this.age = age;
    this.getAge = function () {
        return this.age;
    }
 }
var father = new Father("Tom");
var son = new Son("Jack",18);
console.log(father.getName());//Tom
console.log(son.getName());//Jack//继承父类getName()方法
console.log(son.getAge());//18
 

多继承(利用对象冒充可以实现多继承)


function FatherA(name) {
    this.name = name ;
    this.getName = function () {
        return this.name;
    }
 }
function FatherB(job) {
    this.job = job;
    this.getJob = function () {
        return this.job;
    }
 }
function Son(name,job,age) {
    this._newMethod = FatherA;
    this._newMethod(name);
    delete  this._newMethod;
    this._newMethod = FatherB;
    this._newMethod(job);
    delete  this._newMethod;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/882e7416256eb145d8b5e8a58ec6a80d.html