首页 \ 问答 \ Javascript中的单例和原型(Singleton and Prototyping in Javascript)

Javascript中的单例和原型(Singleton and Prototyping in Javascript)

我只是在研究用JavaScript定义单例的方法,在查看了几个示例后,我想到了以下我没有找到的方法:

function MyClass() {
   if (MyClass._sharedInstance === undefined) {
      // actual constructor code

      MyClass._sharedInstance = this;
   }
   return MyClass._sharedInstance;
}

MyClass._sharedInstance = undefined;

似乎工作得很好......但我无法在任何地方找到这一点的事实让我怀疑。 有没有理由不以这种方式做单身,特别是考虑到JavaScript的许多小陷阱。 我知道通过简单地做一个var MyClass = { /* MyClass Stuff */ }我可以用更少的代码实现一个单例,但为了保持一致性,我想用原型定义所有类。


I was just looking into ways of defining singletons in JavaScript, and after looking into a few samples I thought about the following way which I haven't found anywhere:

function MyClass() {
   if (MyClass._sharedInstance === undefined) {
      // actual constructor code

      MyClass._sharedInstance = this;
   }
   return MyClass._sharedInstance;
}

MyClass._sharedInstance = undefined;

Seems to work fine... but the fact that I couldn't find this anywhere makes me suspicious. Is there any reason not to do a singleton that way, especially considering the many little pitfalls of JavaScript. I know that by simply doing a var MyClass = { /* MyClass Stuff */ } I can achieve a singleton with less code, but for the sake of consistency I would like to define all my classes using prototypes.


原文:
更新时间:2022-07-24 09:07

最满意答案

从Firebug获得的路径是XPath表达式。 最好使用一个允许您直接使用xpath的解析器。 我喜欢使用lxml及其etree接口:

from lxml import etree
tree = etree.parse(yourfile)
lucky = tree.xpath('/html/body/center/span/center/div[2]/form/div[2]/div[3]/center/input[2]')

The path you get from Firebug is an XPath expression. It's best to use a parser that lets you use xpath directly. I like using lxml with its etree interface:

from lxml import etree
tree = etree.parse(yourfile)
lucky = tree.xpath('/html/body/center/span/center/div[2]/form/div[2]/div[3]/center/input[2]')

相关问答

更多
  • AttributeError: 'NoneType' object has no attribute 'findAll' 意思是: 此处的top_div是个空值,即在Python中是None,所以是NodeType 对于一个None的值,当然没有对应的findAll的方法了 (只有正常的,非空的BeautifulSoup类型的变量才有此方法) 所以推出: soup.find('div', {'id':'a'}) 获得值top_div是空的 原因: 要么是你处理的html源码,此处即parser,得到的不是你 ...
  • 您正在运行for循环,以便将'pn'值与'main'值的for循环分开。 具体来说,当您的代码到达第二个for循环时,前一个for循环已经完全执行。 这导致变量pn2被赋予for循环返回的最后一个值。 你可能想要做类似的事情 pn2 = [] for pn in soup.find('table',{"class":"mod_products_grid_listing"}).find_all('span',{"class":"product_code"}): pn2.append(pn.te ...
  • for i in soup.findAll(...): i.find("h3").find("span").find("a") for i in soup.findAll(...): i.find("h3").find("span").find("a")
  • 您没有将属性选择字典传递给find_all()函数。 更换: for part in soup.find_all('td'),{"class":"column-1"}: 有: for part in soup.find_all('td', {"class":"column-1"}): 现在您的代码将产生: 17103 17104 You are not passing the attribute selection dictionary into the find_all() function. Re ...
  • 您将需要使用硒而不是普通的请求库。 请注意,我无法发布所有的输出,因为解析的HTML非常庞大。 码: from bs4 import BeautifulSoup from selenium import webdriver driver = webdriver.Chrome() driver.get("https://theunderminejournal.com/#eu/sylvanas/item/124105") bsObj = BeautifulSoup(driver.page_source,'ht ...
  • 好。 这是解决方案, 首先,确保你安装了'beautifulsoup4': http : //www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-beautiful-soup 这是获取所有正文和主题标签的代码: from bs4 import BeautifulSoup html_doc= """
    oil, gas body text
  • wind变量是一个类文件对象,它不包含findAll方法。 如果你想要BeautifulSoup,你需要从页面内容创建一个新的“汤”: from bs4 import BeautifulSoup import urllib2 html = urllib2.urlopen('http://w1.weather.gov/data/obhistory/KCQX.html').read() wind = BeautifulSoup(html) BeautifulSoup的构造函数也可以采用类文件对象,因此可以删 ...
  • 该错误不在您提供的代码示例中:如错误消息所示,您已调用findCSV函数findCSV传递字符串。 # you did this: my_string = "hello" findCSV(my_string) # instead of soup = BeautifulSoup('') findCSV(soup) The bug is not in the code sample that you have provided: as the error messa ...
  • 从Firebug获得的路径是XPath表达式。 最好使用一个允许您直接使用xpath的解析器。 我喜欢使用lxml及其etree接口: from lxml import etree tree = etree.parse(yourfile) lucky = tree.xpath('/html/body/center/span/center/div[2]/form/div[2]/div[3]/center/input[2]') The path you get from Firebug is an XPath ...
  • 怎么样: inTopic = urllib2.urlopen('http://stackoverflow.com/questions/4951331/how-do-i-insert-an-attribute-using-beautifulsoup') content = BeautifulSoup.BeautifulSoup(inTopic) tlist = content.findAll('table') for tbl in tlist: tbl.attrs.append(('border', ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。