gpt4 book ai didi

javascript - JavaScript OOP 中的公共(public)方法

转载 作者:行者123 更新时间:2023-11-30 07:16:28 26 4
gpt4 key购买 nike

我想创建一个 javascript 类,其中包含我可以在类内和类外调用的方法。如果您愿意,我想制作一个“公共(public)”方法。我希望 getTextAreaElementappendTextArea 是这样的方法。

我已经展示了迄今为止我能想出的最佳代码片段。我还尝试将方法定义为原型(prototype)以及在类中 (this.func = ...)。但这只允许我在外部调用方法(new Socket().appendTextArea("osgjr89");),但不能在类本身内!下面的代码片段显示了完全相反的实现,我无法在类外部调用方法,但可以在类内调用它。

错误:

Uncaught TypeError: Object #Socket has no method 'appendTextArea'

套接字.js:

function Socket() {
var socket;
var canvas = document.getElementById('c');
var context = canvas.getContext("2d");

if (window.WebSocket) {
socket = new WebSocket("ws://localhost:9012/websocket");
socket.binaryType = 'arraybuffer';
socket.onopen = onopen;
socket.onmessage = onmessage;
socket.onerror = onerror;
socket.onclose = onclose;
} else {
alert("Your browser does not support Web Socket.");
}

function getTextAreaElement() {
return document.getElementById('responseText');
}

function appendTextArea(newData) {
var el = getTextAreaElement();
el.value = el.value + '\n' + newData + " :)";
}

function onopen(event) {
getTextAreaElement().value = "Web Socket opened!";
}
/*[...]*/
}

main.js(在 socket.js 之后加载)

$(document).ready(function() {
var s = new Socket();
s.appendTextArea("osgjr89"); // ERROR!
});

更新的 socket.js:

function Socket() {
[...]
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:9012/websocket");
socket.binaryType = 'arraybuffer';
socket.onopen = this.onopen;
socket.onmessage = this.onmessage;
socket.onerror = this.onerror;
socket.onclose = this.onclose;
} else {
alert("Your browser does not support Web Socket.");
}

this.getTextAreaElement = function() {
return document.getElementById('responseText');
}

this.appendTextArea = function(newData) {
var el = this.getTextAreaElement();
el.value = el.value + '\n' + newData + " :)";
}

this.onopen = function(event) {
this.getTextAreaElement().value = "Web Socket opened!";
}
[...]
}

最佳答案

所有公共(public)方法都必须声明为属性,而不是变量/函数。所以,你必须改变这样的东西:

function getTextAreaElement() {
return document.getElementById('responseText');
}

进入

this.getTextAreaElement = function() {
return document.getElementById('responseText');
}

关于javascript - JavaScript OOP 中的公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14940845/

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