文章加密

;

2024年12月2日 星期一

constructor, __proto__, prototype

https://www.lagagain.com/post/7%E5%A4%A9%E6%90%9E%E6%87%82js%E9%80%B2%E9%9A%8E%E8%AD%B0%E9%A1%8Cday02-new-factory/


題目

function FooConstructor(name){

  this.name = name;

  this.hello = function(){

     console.log(`Hello, ${this.name}`);

  }

}


var obj2 = new FooConstructor("Foo");


var obj3 = {};

obj3.constructor = FooConstructor;

obj3.constructor("Kitty");

obj3.hello(); // => Hello, Kitty


var obj4 = {};

obj4.__proto__ = FooConstructor.prototype;

obj4.constructor("K-on"); 

obj4.hello(); // => Hello, K-on


Object.is(obj3.constructor, obj4.constructor);  // true


考題

FooConstructor.prototype.bye = function(){console.log(`Bye Bye, ${this.name}`)};

obj2.bye(); // => Bye Bye, Foo

// obj3.bye(); // error! 沒繼承到`FooConstructor`,不受影響

obj4.bye(); // => Bye Bye, K-on



var name; // just declare
console.log(name); // => underfined

FooConstructor("JavaScript");  // 沒寫到new

// Oops! 怎麼被改到了??   
console.log(name);  // Javascript


可以改寫func如下避免:

The new.target meta-property lets you detect whether a function or constructor was called using the new operator. 


function FooConstructor(name){

  if (!new.target) throw "FooConstructor() must be called with new";

  this.name = name;

  this.hello = function(){

     console.log(`Hello, ${this.name}`);

  }

}



In JavaScript, __proto__ and prototype are related but distinct concepts that serve different purposes. Here's an explanation of each and their differences:

1. __proto__ (Dunder Proto)

  • Definition: __proto__ is an object property that points to the prototype of the object it belongs to.
  • Purpose: It is used to establish the prototype chain, which is central to JavaScript's inheritance model.
  • Access: Every object in JavaScript has a __proto__ property (except objects created with Object.create(null)).
  • Use: You can access or set an object's prototype dynamically with __proto__. However, it's non-standard in modern JavaScript and is replaced by Object.getPrototypeOf() and Object.setPrototypeOf().

Example

const obj = {}; const proto = { greeting: 'Hello' }; obj.__proto__ = proto; console.log(obj.greeting); // "Hello" (inherited from proto)


2. prototype

  • Definition: prototype is a property of functions (specifically, constructor functions) and not of objects. It defines the blueprint for creating new objects using the new keyword.
  • Purpose: The prototype object contains properties and methods that will be inherited by all instances created from the constructor function.
  • Use: When you create an object using a constructor function, the object’s __proto__ points to the constructor's prototype.

Example

function Person(name) { this.name = name; } Person.prototype.sayHello = function () { console.log(`Hello, my name is ${this.name}`); }; const john = new Person('John'); john.sayHello(); // "Hello, my name is John" console.log(john.__proto__ === Person.prototype); // true

Key Differences

Feature__proto__prototype
TypeProperty on all objectsProperty on functions
PurposeLinks an object to its prototypeDefines properties for objects created by a constructor function
AccessibilityDirectly on any objectOnly exists on constructor functions
Relationobj.__proto__ references the prototype of the object's constructor functionUsed to create objects' prototype chains

Practical Relationship

When an object is created using a constructor function, the object's __proto__ is set to the constructor function's prototype. This establishes the inheritance chain.

Example

function Animal(species) { this.species = species; } Animal.prototype.speak = function () { console.log(`${this.species} makes a sound.`); }; const dog = new Animal('Dog'); // Relationships console.log(dog.__proto__ === Animal.prototype); // true console.log(Animal.prototype.constructor === Animal); // true console.log(dog.constructor === Animal); // true

When to Use

  • Use prototype: When defining methods or properties that should be shared among all instances of a constructor function.
  • Avoid using __proto__: While useful for learning, modern JavaScript recommends using Object.getPrototypeOf() and Object.setPrototypeOf() for better performance and standards compliance.

__proto__ is a more dynamic and less formalized way to access prototypes, while prototype is a structured mechanism for defining and sharing behaviors in object-oriented programming.


看下ai的 好幾個問題回答沒仔細看









沒有留言:

張貼留言