gpt4 book ai didi

javascript - 在 'this' 和对象的原型(prototype)方法中使用 'constructor' 时如何正确返回值?

转载 作者:行者123 更新时间:2023-12-02 15:52:58 25 4
gpt4 key购买 nike

有关实时代码示例,请查看我的:Codepen

问题:如何确保 p1.prototype.setFirst()p1.prototype.fullName() 返回正确的仍然使用 this 时的值?

var Person = function(){
this.firstName = "Penelope";
this.lastName = "Barrymore";

}
Person.prototype.fullName = function () {
return this.firstName + " " + this.lastName;
}
Person.prototype.setFirst = function () {
return this.firstName = "mark"
}
var p1 = new Person();
p1.prototype.setFirst()
console.log(p1.prototype.fullName());

最佳答案

如果您确实必须通过这样的原型(prototype)进行调用,您可以这样做:

Person.prototype.setFirst.call(p1);

...和:

Person.prototype.fullName.call(p1);

callapply 是更改 this 的最简单方法。

如果您想要引用 this 绑定(bind)到它的函数版本,请使用 bind:

var myFullName = Person.prototype.fullName.bind(p1);
myFullName(); // this will be p1

...但是当然,这是很自然的事情:

p1.fullName()

而如果想通过对象获取原型(prototype),可以使用:

p1.__proto__

...或:

p1.constructor.prototype

关于javascript - 在 'this' 和对象的原型(prototype)方法中使用 'constructor' 时如何正确返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31750701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com