gpt4 book ai didi

javascript - 原型(prototype)对象

转载 作者:行者123 更新时间:2023-12-02 19:33:04 24 4
gpt4 key购买 nike

我对原型(prototype)不太熟悉,我确信这是不正确的实现,但我整理了一个我想要实现的小例子。

我可以将原型(prototype)设为文字对象而不是函数,但我遇到了无法访问我正在创建原型(prototype)的对象(在本例中为 Person)内部的变量/属性的问题。

Person = function() {
this.name = 'mike';
this.departureSaying = 'Adios amigo!';
}

Person.prototype.say = function() {
var self = this;
function hello() { alert('hello my name is ' + self.name); }
function goodbye() { alert(self.departureSaying); }
}

var mike = new Person();
mike.say.hello();
mike.say.goodbye();

如果你运行这个,你会得到 Object has no method hello and goodbye。

最佳答案

您的两个函数是该方法的本地函数;你不会归还它们。

Person.prototype.say = function() {
var self = this;

return {
hello: function() { alert('hello my name is ' + self.name); },
goodbye: function() { alert(self.departureSaying); }
};
};

然后你会想要:

mike.say().hello();
mike.say().goodbye();

但是,我不认为使用原型(prototype)适合这种情况。相反,请在构造函数中分配它:

function Person() {
var self = this;

this.name = 'mike';
this.departureSaying = 'Adios amigo!';

this.say = {
hello: function() { alert('hello my name is ' + self.name); },
goodbye: function() { alert(self.departureSaying); }
};
}

Here's a demo.

关于javascript - 原型(prototype)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11278774/

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