所以这些年来我终于停止了我的脚,并决定"正确"学习JavaScript.语言设计中最令人头疼的元素之一是它的继承实现.有Ruby经验,我很高兴看到闭包和动态打字; 但是对于我的生活来说,无法弄清楚使用其他实例进行继承的对象实例会带来什么好处.
javascript oop inheritance language-design prototype-programming
我试图理解链接函数在JavaScript中是如何工作的.我有两个例子:
第一
class Arithmetic {
constructor() {
this.value = 0;
}
add(value) {
this.value = this.value + value;
return this;
}
subtract(value) {
this.value = this.value - value;
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过实例化let a = new arithmetic();和链接方法a.add(3).subtract(4);
第二
var zappo = function(selector) {
var el;
var obj = {
getEl(selector) {
return document.querySelector(selector);
},
addClass(className){
el.classList.add(className);
return this;
}
}
el = getEl(selector);
return obj;
}
Run Code Online (Sandbox Code Playgroud)
我可以通过链接这些方法 zappo(#main).addClass("green").addClass("red");
我的问题是为什么第一个构造函数能够在没有对象内的方法的情况下链接函数,而第二个函数需要所有方法都在一个对象中?