我试图深入了解原型继承和类创建(我知道,还有其他方法,但为了这个目的,我试图掌握原型.)我的问题是:使用下面的代码示例,是有没有办法内部创建私有变量Tree,并Fruit不会与该函数返回,但仍是原型函数访问genus和bulk?
var Tree = function ( name, size ) {
this.name = name;
this.size = size;
};
Tree.prototype.genus = function(){
return ((typeof this.name !== 'undefined') ? this.name : 'Hybridicus Maximus');
};
Tree.prototype.bulk = function(){
return ((typeof this.size !== 'undefined') ? this.size : '8') + ' ft';
};
var Fruit = function( name, size ) {
this.name = name;
this.size = size;
};
Fruit.prototype = new Tree();
// Fruit.prototype = Tree.prototype; -- I …Run Code Online (Sandbox Code Playgroud) 今天,我看到了我一生中从未见过的JavaScript模式.我无法说出使用这种模式的目的.这对我来说似乎不对,但我想保守一点.这可能是我以前从未见过的一些很棒的模式.
function Dog() {
Dog.prototype.bark = function () {
alert('woof!');
}
this.bark = function () {
Dog.prototype.bark();
}
this.bark();
}
Run Code Online (Sandbox Code Playgroud)
首先,我不是没有理由在构造函数中创建方法(作为特权成员)的粉丝.每次创建实例时都会导致创建函数.其次,在这段代码片段中,它还调用原型名称"Dog",而不是"this".这让我非常困惑.
谁知道它有什么好处?
谢谢!恩典
我一直在寻找一个明确的答案,弹出的大部分内容仍然与旧的(或者我应该说"传统的")方式相关function.
根据这个SO答案,
ES2015不支持类属性.
据我所知,向类中添加静态变量的唯一方法是:
https://jsfiddle.net/abalter/fknwx3n4/
class C {
constructor(x) {
console.log("in constructor " + x);
this.x = x;
this.add(this.x);
}
add(x) {
console.log("in add " + x);
C.alist.push(x);
}
show() {
console.log("in show");
console.log(C.alist);
}
}
// MUST be done outside of actual class definition.
C.alist = [];
c1 = new C(5);
c1.show();
c2 = new C(10);
c1.show();
c2.show();
Run Code Online (Sandbox Code Playgroud)
这是故事的结尾吗?在类定义中无法做到这一点似乎很奇怪.
TL; DR? 为什么我不能在构造函数中覆盖构造函数的原型?
我正在弄清楚我的原型继承模式.我不喜欢原型通常是从构造函数外部定义的,并希望逻辑上更好地封装事物.
我发现我期望工作的一条神奇的线路没有.
function Orifice(){
this.exhaust=function(){};
this.ingest=function(){};
}
var standardOrifice = new Orifice();
function Sphincter(){
this.constructor.prototype = standardOrifice; // <-- does not work
this.relax=function(){};
this.tighten=function(){};
}
Run Code Online (Sandbox Code Playgroud)
有趣的是,我可以编写单独的属性this.constructor.prototype,但是我不能像构造函数定义之外那样覆盖整个原型对象.
所以像这样的东西工作:
this.constructor.prototype.exhaust = standardOrifice.exhaust;
this.constructor.prototype.ingest = standardOrifice.ingest;
Run Code Online (Sandbox Code Playgroud)
为此我可以创建一个简单的克隆函数来处理这个:
function extend(target){
return {
from: function(obj){
target.__proto__ = obj.constructor.prototype;
for (key in obj) if (obj.hasOwnProperty(key)) target[key]=obj[key];
return target;
}
};
}
Run Code Online (Sandbox Code Playgroud)
值得庆幸的是,到目前为止,在我的测试中,这种技术似乎运行良好,但我不确定是否存在我可能遗漏的细节或性能案例.
function Sphincter(){
extend(this.constructor.prototype).from(standardOrifice);
//...
}
Run Code Online (Sandbox Code Playgroud)
为什么我不能在构造函数中覆盖构造函数的原型?但我可以在构造函数之外?单独编写属性是否在构造函数中起作用?