Это очень просто и понятно.Посмотри на код.Попытайтесь понять базовую концепцию, лежащую в основе расширения javascript.
Сначала давайте расширим функцию javascript.
function Base(props) {
const _props = props
this.getProps = () => _props
// We can make method private by not binding it to this object.
// Hence it is not exposed when we return this.
const privateMethod = () => "do internal stuff"
return this
}
Вы можете расширить эту функцию, создав дочернюю функцию следующим образом
function Child(props) {
const parent = Base(props)
this.getMessage = () => `Message is ${parent.getProps()}`;
// You can remove the line below to extend as in private inheritance,
// not exposing parent function properties and method.
this.prototype = parent
return this
}
Теперь вы можете использовать дочернюю функцию следующим образом:
let childObject = Child("Secret Message")
console.log(childObject.getMessage()) // logs "Message is Secret Message"
console.log(childObject.getProps()) // logs "Secret Message"
Мы также можем создать функцию Javascript, расширив классы Javascript следующим образом.
class BaseClass {
constructor(props) {
this.props = props
// You can remove the line below to make getProps method private.
// As it will not be binded to this, but let it be
this.getProps = this.getProps.bind(this)
}
getProps() {
return this.props
}
}
Давайте расширим этот класс с помощьюДочерняя функция, подобная этой,
function Child(props) {
let parent = new BaseClass(props)
const getMessage = () => `Message is ${parent.getProps()}`;
return { ...parent, getMessage} // I have used spread operator.
}
Опять же, вы можете использовать дочернюю функцию следующим образом, чтобы получить похожий результат,
let childObject = Child("Secret Message")
console.log(childObject.getMessage()) // logs "Message is Secret Message"
console.log(childObject.getProps()) // logs "Secret Message"
Javascript - очень простой язык.Мы можем сделать что угодно.Удачной JavaScripting ... Надеюсь, я смог дать вам идею использовать в вашем случае.