开发者

Object function is passed as argument, how access parent object in that function?

I have the following situation:

function dog()
{
    this.name = 'Lumpy';
    this.getName = function() {
        return this.name;
    }
}

function show_dog_name(dogname)
{
    alert(dogname());
}

bigdog = new dog();
show_dog_name(bigdog.g开发者_JS百科etName);

"this" not refers to "dog" object so how get parent object in passed function.


var that = this;
this.getName = function() { return that.name; };


Try this:

function dog(){
    this.name = 'Lumpy';
    var obj=this;
    this.getName = function() {
        return obj.name;
    }
}

function show_dog_name(dogname){
    alert(dogname());
}

bigdog = new dog();
show_dog_name(bigdog.getName);


You can create dog like this:

function dog()
{
    var name = 'Lumpy';
    this.getName = function() {
        return name;
    }
}

This create a closure that allow you getName to always be able to access name.
If you want the dog name to be 'public' to your object, you can use:

var name = 'Lumpy';
this.name = name;

Another solution consist to make the 'right' this object always available for your getName function:

var dogObj = this;
this.name = 'Lumpy';
this.getName = function() {
  return dogObj.name;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜