Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - Is Object.defineProperty() preferable over setting the constructor directly when inheriting from a base constructor function

When subclassing a function constructor, is it preferable to use defineProperty() instead of setting the constructor equal to the base class directly? I've seen both and I am a bit confused about the difference between the two (both seem to allow attributes and methods to be inherited, but one is more readable).

For example:

function Person(first, last, age, gender, interests) {
    this.name = {
        'first': first,
        'last': last
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
}

Person.prototype.greeting = function() {
    console.log(`Hello from ${this.name.first} ${this.name.last} from inside Person!`);
};


function Teacher(first, last, age, gender, interests, subject) {
    Person.call(this, first, last, age, gender, interests);

    this.subject = subject;
}

Teacher.prototype = Object.create(Person.prototype);

Object.defineProperty(Teacher.prototype, 'constructor', {
    value: Teacher,
    enumerable: false, // so that it does not appear in 'for in' loop
    writable: true
});

// Teacher.prototype.constructor = Person;

let teacher = new Teacher('Bob', 'Smith', 32, 'male', ['music', 'skiing'], 'Math');
teacher.greeting();
console.log(teacher.subject);

I've seen this used:

Object.defineProperty(Teacher.prototype, 'constructor', {
    value: Teacher,
    enumerable: false, // so that it does not appear in 'for in' loop
    writable: true
});

as well as this:

Teacher.prototype.constructor = Person;

Which is preferable and why?

question from:https://stackoverflow.com/questions/65894332/is-object-defineproperty-preferable-over-setting-the-constructor-directly-when

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are reading it wronge. defineProperty() will add a new Property on a Object which shall be avaiable to that object only, even if the Object was inherited.

Here is a Example

    //Empty Object
    const bill = {};
    
    bill.defineProperty(bill, 'total', {
      value: 42,
      writable: false
    });
    
    bill.total= 77;
    // throws an error in strict mode
    
    console.log(bill.total);
    // expected output: 42

if you make writable: true you can add new values to it so basically, using defineProperty should be used for creating OR Defining a New Property on Empty/Copied or any other version of Object(s) Individually

Whereas For Create() will create a entierly new Object based on a exisiting Obj with exisiting Properties(basically a xerox copy of the Object).

Here is the example

const fetus= {
  isHuman: false,
  printIntroduction: function() {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};
const me = Object.create(fetus);

me.name = 'Indiana'; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten

me.printIntroduction();
// expected output: "My name is Indiana. Am I human? true"

Here in the create() example i can use define Property on me to set a last name

Object.defineProperty(me, 'lastName', {
  value: Jones,
  writable: true
});

This way now my fetus Obj is different than me Obj

Hence, When it comes to Prefrence.. there is none.. it will depend on use case to use case basis. (Ideally whichever works :) ) for that app or function


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...