未定义对象方法

Undefined Object method

本文关键字:方法 对象 未定义      更新时间:2023-09-26

我有这个代码,当我使用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;
}