This JavaScript syntax I haven't seen till now, what does it do really?
今天我看到了一个我不熟悉的JavaScript语法(在调用函数时)。 它就像:
1 2 3 4 | def('Person') ({ init: function(name) {this.name=name;} ,speak: function(text) {alert(text || 'Hi, my name is ' + this.name);} }); |
,和
1 2 3 | def('Ninja') << Person ({ kick: function() {this.speak('I kick u!');} }); |
1:第一个例子中括号内的对象会发生什么? 它以某种方式由
2:关于同样的事情,但是使用了我从未见过的
代码来自http://gist.github.com/474994,其中Joe Dalton做了一个小的JavaScript-OO继承的事情(它显然是别人工作的一个分支,但看起来很彻底改写)。 也许你想在那里查看
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | function def(klassName, context) { context || (context = global); // Create class on given context (defaults to global object) var Klass = context[klassName] = function Klass() { // Called as a constructor if (this != context) { // Allow the init method to return a different class/object return this.init && this.init.apply(this, arguments); } // Called as a method // defer setup of superclass and plugins deferred._super = Klass; deferred._plugins = arguments[0] || { }; }; // Add static helper method Klass.addPlugins = addPlugins; // Called as function when not // inheriting from a superclass deferred = function(plugins) { return Klass.addPlugins(plugins); }; // valueOf is called to set up // inheritance from a superclass deferred.valueOf = function() { var Superclass = deferred._super; if (!Superclass) return Klass; Subclass.prototype = Superclass.prototype; Klass.prototype = new Subclass; Klass.superclass = Superclass; Klass.prototype.constructor = Klass; return Klass.addPlugins(deferred._plugins); }; return deferred; } |
1:调用
1 2 3 4 5 | function x() { return function(y) { alert(y); } } x()('Hello world!'); |
2:
编辑:
正如蒂姆解释的那样,移位运算符仅用于引发对
哇,这让我的小脑子理解得足够复杂,但是现在我知道它是如何工作的我感觉好多了:)感谢@Tim指出
使用以下方法创建
1 2 3 4 | def ("ClassName") ({ init: function() { .. }, foo: function() { .. } }); |
因为第一次调用
使用
1 | def("ClassName") << ParentClass({ .. }) |
将评估如下:
代码试图模拟Ruby语法来创建子类,如下所示:
1 2 3 4 5 | class Child < Parent def someMethod ... end end |