Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS中的继承:this.base=Class();这个.base()还是。。。?_Javascript_Inheritance - Fatal编程技术网

Javascript JS中的继承:this.base=Class();这个.base()还是。。。?

Javascript JS中的继承:this.base=Class();这个.base()还是。。。?,javascript,inheritance,Javascript,Inheritance,我试图在JS中“获取”继承。 我刚刚发现了一种简单的方法,可以将所有属性从一个对象复制到另一个对象: function Person(name){ this.name="Mr or Miss: "+name; this.introduce = function(){ console.log("Hi, I am "+this.name); } } function Employee(name,title){ this.title=title; this.base=

我试图在JS中“获取”继承。 我刚刚发现了一种简单的方法,可以将所有属性从一个对象复制到另一个对象:

function Person(name){
  this.name="Mr or Miss: "+name;

  this.introduce = function(){
    console.log("Hi, I am "+this.name);
  }
}

function Employee(name,title){
  this.title=title;

  this.base=Person;
  this.base(name);  

}

e = new Employee('tony', 'manager')
e.introduce();
注意,我有一个带有构造函数的Person()类,其属性“name”由构造函数生成。 这样做的好处是employee在构造函数中也有名称——瞧,它使用相同的参数创建Person对象

如果我用“原型”的方式来做这件事:

呃。。。。现在怎么办?我甚至无法完成此操作:无法使用正确的Person构造函数设置Employee中的this.name;Person对象的创建在继承中只发生一次

所以。。。我错过了什么?在我的案例中,我给出的第一个例子是“正确的”方法吗?有没有一种方法可以得到与第二个例子相同的结果


救命啊

这种原型继承通常是这样做的:

function Parent() {}

function Child() {
    Parent.call(this); // call the constructor of the parent
}

var Constr = function() {};
Constr.prototype = Parent.prototype;

Child.prototype = new Constr();
Child.prototype.constructor = Child;
因此,“技巧”是将
父.prototype
指定为一个空函数的prototype,并将此函数的新实例设置为
子函数的prototype

这样做是为了扩展
子.prototype
不会扩展
父.prototype

您还必须在子构造函数中调用父构造函数。我猜这就是你挣扎的部分。每个函数都有一个和方法,让您显式地设置函数中应该引用的元素
this

在您的示例中,它看起来像:

function Employee(name,title){
  this.title=title;

  Person.call(this, name);
}
不将构造函数分配给实例的属性

在您的示例中,
this.base(name)
起作用,因为通过将构造函数分配给实例的属性(并以这种方式调用),函数中的
引用该实例


有几个库实现此模式,例如:


我完全理解谷歌闭包库中的功能(哇,我一定有进展了:D),但是!据我所知,当我创建派生类时,是否要继承内部属性取决于我,键入Parent.call(this);或者父母。叫(这个,名字)--对吗?托尼:我想你会的。但是,如果您考虑了经典继承(如Java),那么如果您覆盖它,您还必须调用父级的构造函数。唯一的区别是,在JavaScript中,基本上总是覆盖构造函数,因为这是我们模拟类的方式。所以事实上并没有什么不同,也许更容易理解发生了什么。
function Employee(name,title){
  this.title=title;

  Person.call(this, name);
}
goog.inherits = function(childCtor, parentCtor) {
  /** @constructor */
  function tempCtor() {};
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  childCtor.prototype.constructor = childCtor;
};