2017-08-06 61 views
0

混乱在仔细检查下面的教程代码JavaScript的原链接在此

Animal = function(name) {this.name = name} 
Animal.prototype.eats = function(){ 
     return this.name + ' is eating' 
} 

Chordate = function(name){Animal.call(this,name)} 

我明白我的问题是如何call作品(基本上,在这种情况下,这成为this)......但是,如何做一个用这个? 我很抱歉,我理解原型是如何工作的。但是,真的,我不明白,一旦你设置Chordate如上所述..人们如何使用它? 这是如何有用?或者你现在如何指定this? 有人可以请示例解释吗?

+0

[MDN(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call)有一些很好的例子当你可能想要使用这个。 – Lavios

+1

Youre missing Chordate.prototype = Object.create(Animal.prototype) –

+0

现在读取MDN ..所以新的Chordate('无论这个如何',arg) – user3502374

回答

1

创建一个链接到Animal的原型方法:

Chordate.prototype = Object.create(Animal.prototype) 

然后new起来:

var c = new Chordate('my name'); 

c.eats(); 

线Animal.call(this,name)就像拨打电话到基本构造。它执行Animal构造函数并传递name,但使用正确的this背景:

Animal = function(name) { 
    // "this" will be your Chordate instance 
    this.name = name 
} 
+0

这有助于我理解这一点。谢谢 – user3502374

0

让我们想象的youre构建动物:

new Animal(); 

和施工期间,它吸取了新的动物到画布。构造函数如下所示:

function Animal(){ 
    canvas.draw(this.x,this.y,this.image); 
    } 

现在你已经有了一只老虎。如果它被修建,老虎应该咆哮。

function Tiger(){ 
    this.roar(); 
} 

现在呢?它的动物是如此加入画布的吗?不可以。由于js继承系统,您需要手动执行此操作。所以,当老虎被构建,还需要构建它作为动物:

Animal.call(this); 

这甚至与新的类语法简单:

class Animal{ 
    constructor(){ 
    this.draw(this.x,this.y,this.image); 
    } 
} 

class Tiger extends Animal{ 
    constructor(){ 
    this.roar(); 
    super()//construct Animal 
    } 
} 
0

这只是意味着是一个加法到其他答案,并且对于评论太长了。

也许它可以帮助你明白什么是new操作实际上做:

var newInstance = new ConstructorFunction(arg1, arg2); 
  1. 创建一个新的对象。此对象的原型是ConstructorFunction.prototype
var newInstance = Object.create(ConstructorFunction.prototype); 
  • 调用ConstructorFunction与新创建的对象:
  • ConstructorFunction.call(newInstance, arg1, arg2); 
    

    如果来自另一个ConstructorFunction继承“类“,它必须调用它的超级构造函数。这就是下面的代码做什么:

    function Parent() { 
        // this === newInstance 
    } 
    
    function Child() { 
        // this === newInstance 
        Parent.call(this); // call the super constructor 
    } 
    
    Child.prototype = Object.create(Parent.prototype); 
    
    var newInstance = new Child(); 
    // or: 
    var newInstance = Object.create(Child.prototype); 
    Child.call(newInstance); // call the constructor, which calls the super constructor 
    
    +0

    真的很喜欢这个.. HOwever,你可以创建没有ConstructorFunction的第一步吗?它可以是Object.create(Object.prototype)?我需要从头开始,而不必依赖以前的任何东西来理解这一点。可以这样吗? – user3502374

    +0

    如果它是'Object.create(Object.prototype)',那么你将不会从'ConstructorFunction.prototype'获得方法。当然,你可以做到这一点,但我不认为这就是你想要的。这不是“新”运营商的工作方式。 – PeterMader

    +0

    真的很喜欢这个角度..但让我回到这..现在阅读更多关于这个话题 – user3502374