未定义对象方法
Undefined Object method
我有这个代码,当我使用display
方法时,它一直给我:
url未定义
name未定义
description未定义
我不知道为什么我得到错误,即使我提供它将所有的礼仪。谁能帮我找出问题所在吗?
function website(name,url,description)
{
//Proparties
this.name=name;
this.url=url;
this.description=description;
// Methods
this.getName=getName;
this.getUrl=getUrl;
this.getDescription=getDescription;
this.display=display;
// GetName Method
function getName(name)
{
this.getName=name;
}
// GetUrl Method
function getUrl(url){
this.getUrl=url;
}
// getDescription
function getDescription(description){
this.getDescription=description;
}
function display(name,url,description){
alert("URL is :" +url +" Name Is :"+name+" description is: "+description);
}
}
// Set Object Proparites
web=new website("mywebsite","http://www.mywebsite.com","my nice website");
// Call Methods
var name = web.getName("mywebsite");
var url = web.getUrl("http://www.mywebsite.com");
var description = web.getDescription("my nice website");
web.display(name,url,description);
我想你对函数的工作方式很困惑。在你的代码中有:
this.getName=getName; // this sets a "getName" method on the "this" object
// to be some function that will be implemented below
function getName(name) // i believe this function shouldn't have any parameter...
{
this.getName=name; //now, you're overriding the "getName" that you set above,
// to be something completely different: the parameter you sent when calling this function!
// instead, you should do:
return name;
}
你的getter函数是覆盖自己的setter (?)将它们改为
function getName(){
return this.name;
}
function getUrl(){
return this.url;
}
function getDescription(){
return this.description;
}
和
function setName(name){
this.name = name;
}
function setUrl(url){
this.url = url;
}
function setDescription(description){
this.description = description;
}
如果您希望setter返回设置值,请在赋值前添加return
关键字。
你想写这个?:
function setName(name)
{
this.name=name;
}
据我所知,您正在设置,而不是获取属性。所以:
var name = web.setName("mywebsite");
我应该将它声明为
function () {
//property
this.name
//method
this.setName = function ( name ) {
this.name = name
}
}
他们实现它的方式,询问上下文问题
你的getter应该返回一个值,而不是重新赋值getter本身,例如
function getName() {
return this.name;
}
每个方法的返回值应该如下所示:
// GetName Method
function getName() {
return this.getName = name;
}
// GetUrl Method
function getUrl() {
return this.getUrl = url;
}
// GetDescription Method
function getDescription() {
return this.getDescription = description;
}
相关文章:
- 序列化数据属性中对象的最可靠方法
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 如何从对象的原型方法访问JavaScript对象属性
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- 设置嵌套对象属性的更好方法
- JQuery示例不起作用-“;对象没有't支持属性或方法'按钮'&”;
- 对象不支持属性或方法“自动完成”
- call()和apply()实际上是用来欺骗方法处理类似数组的对象的
- 对象文字方法上的Javascript绑定不起作用
- Meteor应用程序无法运行-对象#<编译器>没有方法'主机'
- 为什么我可以在Array属性对象中找到Javascript Array for Each方法
- Underscore.js某些对象的所有方法的总和
- 对象#<XMLHttpRequest>没有方法'完成'
- Es6:能够在设置/更新/删除对象属性时调用自定义方法
- 丢失对象“;这个“;方法中的上下文
- 如何在ajax中调用javascript对象的方法
- 为什么页面方法对象未定义
- 如何使用在另一个文件中定义的JavaScript方法/对象
- 如何告诉JsHint忽略“未解析的函数或方法”?对象上的警告
- 使用jinja/javascript动态创建方法/对象