gpt4 book ai didi

javascript - 使用对象在 JavaScript 中添加多个 "public functions"

转载 作者:行者123 更新时间:2023-11-29 20:01:16 24 4
gpt4 key购买 nike

众所周知,在 JavaScript 中没有实际的

但是,您可以使用一个简单的函数来创建一个类似于设置的类。

例如:

var Person = function(name){//class like function
this.name = name;//public

var display = function(text){//private
return text;
}

this.getDressed = function(){//public
return display(this.name + " needs to get dressed.");
}

};
var person = new Person("John"),
name = person.name,//returns "John"
dressed = person.getDressed();//returns "John needs to get dressed",
show = person.display("Hello");//throws error "Uncaught TypeError: Object [object Object] has no method 'display'" because there is no such function because it was private.

我的“类”将有很多功能,我想知道是否有办法做类似的事情(我知道这是行不通的):

this = {
fun1: function () {},
fun2: function () {},
fun3: function () {}
}

因为我发现这样做:

this.fun1 = function(){};
this.fun2 = function(){};
this.fun3 = function(){};

很丑。有没有办法将我的所有函数保存在一个对象中,然后附加到 this

最佳答案

如果你不需要访问私有(private)成员,你可以这样做:

function Person(){
//stuff
}

Person.prototype = {
fun1:function(){},
fun2:function(){},
//etc
};

您仍然可以从原型(prototype)函数中访问 this

或者,您可以这样做:

function Person(name){
var display = function(){//stuff};

return {
name: name,
fun1: function(){},
fun2: function(){}
};
}

关于javascript - 使用对象在 JavaScript 中添加多个 "public functions",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14389846/

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