[英]Javascript - How can I change scope and access method without 'this'
I want to port domjs for browser. 我想将domjs移植到浏览器。
var mytemplate = function () {
header(
h1('Heading'),
h2('Subheading'));
nav(
ul({ 'class': 'breadcrumbs' },
li(a({ href: '/' }, 'Home')),
li(a({ href: '/section/'}, 'Section')),
li(a('Subject'))));
article(
p('Lorem ipsum...'));
footer('Footer stuff');
};
But I don't know how to attach some methods like 'header' 'h1' 'h2' to 'mytemplate'. 但是我不知道如何将“ header”,“ h1”,“ h2”之类的方法附加到“ mytemplate”中。
How can I use header() without 'this' keyword. 如何不使用'this'关键字的header()。
Failed Case: 失败的案例:
template.apply($funcs),
template.bind($funcs)(),
template.call($funcs),
I can't use header(), in template. 我不能在模板中使用header()。 (In this case, 'this.header' was available)
(在这种情况下,“ this.header”可用)
First you should check the documentation : 首先,您应该检查文档 :
var domjs = require('domjs/lib/html5')(document);
// Execute mytemplate with h1, h2 etc. functions attached
var mydom = domjs.build(mytemplate);
console.log(mydom.firstChild.nodeName); // header
If you're asking how does it work (?) as you have some custom handling in mind - It works by polluting the global scope for the time of function being called. 如果您想知道它的工作方式(?),因为您要记住一些自定义处理-它通过在调用函数时污染全局范围来起作用。 You can see how it's done here -> https://github.com/medikoo/domjs/blob/v0.2.3/lib/dscope.js#L32-L36
您可以在此处查看其操作方式-> https://github.com/medikoo/domjs/blob/v0.2.3/lib/dscope.js#L32-L36
btw. 顺便说一句。 at all times you can access all those functions on
domjs.map
as domjs.map.header
, domjs.map.h1
etc. 您可以随时访问
domjs.map
上的所有这些函数,例如domjs.map.header
, domjs.map.h1
等。
Method of using global scope, is controversial and has it's downsides (eg functions are not available after function returns) and in upcoming version of domjs this method would no longer be used. 使用全局范围的方法是有争议的,并且具有缺点(例如,函数返回后无法使用函数),在即将发布的domjs版本中,将不再使用该方法。 As an alternative Webmake (and possibly Browserify ) plugins would be provided, so domjs templates can be bundled with those functions assured in local scope, then things will work natural way.
作为替代方法 ,将提供Webmake (可能还有Browserify )插件,因此domjs模板可以与在本地范围内确保的那些功能捆绑在一起,然后事情就可以自然地工作了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.