
New self vs. new static?
1 Expert Answer
Rui K. answered 05/05/23
Seasoned Online Tutor & JavaScript Expert
If you convert return new static($options)
to return new self($options)
, you may not get the same results as there is a difference between new self
and new static
.
When using new self
, the object will always be an instance of the class where it was defined, regardless of any inheritance that takes place. On the other hand, when using new static
, the object will be an instance of the class where it is called, which can be useful for inheritance purposes.
Here's an example to illustrate the difference:
In the above example, createSelf()
method returns an instance of ParentClass
because self
refers to the class where it is defined, which is ParentClass
. However, the createStatic()
method returns an instance of ChildClass
because static
refers to the class where it is called, which in this case is ChildClass
.
So, if you change return new static($options)
to return new self($options)
, you may end up with an object that is not correctly inheriting properties or methods from child classes, since self
always refers to the class where it is defined, whereas static
refers to the class where it is called.
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Brandon G.
Hello, has this issue been resolved?12/04/20