gpt4 book ai didi

javascript - 我可以定义一个方法并为其赋值,并在对象字面量内分配其他方法吗?

转载 作者:行者123 更新时间:2023-11-28 06:46:59 25 4
gpt4 key购买 nike

我知道我可以完美地做到这一点:

var Objeto = {};
Objeto.method = function(){alert("a method of \"Objeto\" ")};

或者这种方式也有效:

var Objeto={method:
{property:"a property inside a method",
method_property:function(){alert(this.property)}
}
};
Objeto.method.method_property();

我也可以这样做,看看我这次想到的与我的问题相关的内容:

var Objeto = {};
Objeto.method = function(){alert("this is a method of \"Objeto\"")};
Objeto.method.property = "this is a property of \"Objeto.method()\" ";
Objeto.method.method_property = function(){alert(Objeto.method.property)};
Objeto.method.method_property();
Objeto.method(); // see I define this method how can I do this with a object literal if possible

现在怎么样,这是我的问题:

var Objeto = {method:function(){
alert("this does not work")};{method_property:function(){
alert("neither this works")};

我的意图:Objeto.method();//警告这不适用于对象文字与我的意图相同:Object.method.method_property();//两者都不起作用,但在上面的方法中我做了同样的事情,那么这样做是错误的吗?

我也知道,如果您还不清楚我的意图,您需要更多地理解我的问题:

var Objeto(){method:function(){{another_method:function(){alert("now how do give value to the method before this inside the literal of course")}}};

var Objeto = {method:{another_method(){alert("works but /"Objeto.method/" is actually a property not method")}}}
Objeto.method.another_method();

问题很简单,我可以给一个方法赋值并在对象文字中分配一个新方法吗?

最佳答案

标准方法是

var Objeto = {
method: function() {
var f = function(){alert("this is a method of \"Objeto\"")};
f.method_property = ...;
return f;
}()
};

};

关于javascript - 我可以定义一个方法并为其赋值,并在对象字面量内分配其他方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33329173/

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