javascript - 使用 call() 进行继承。为什么它会持续存在?

标签 javascript prototypal-inheritance

我一直在回顾几个在 javascript 中使用原型(prototype)继承的示例。

虽然我理解了它的主要内容,但在这些示例中我仍然不完全理解为什么在调用 call() 方法后,当我们随后创建新实例时,其效果仍然存在。

示例代码来自 https://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/

var asCircle = function() {
  this.area = function() {
    return Math.PI * this.radius * this.radius;
  };
  this.grow = function() {
    this.radius++;
  };
  this.shrink = function() {
    this.radius--;
  };
  return this;
};

var Circle = function(radius) {
    this.radius = radius;
};
asCircle.call(Circle.prototype);
var circle1 = new Circle(5);
circle1.area(); //78.54

我认为 call() 在调用它的同一时刻分配了这个范围,并且仅在那一刻。 但是,在调用 call() 后,我们创建了 Circle (circle1) 的实例,并且 Circle1 仍然“记住”使用 Circle 原型(prototype)来使用 asCircle 方法。

我更好地理解每次创建实例时调用 call() 时的类似方法。它会像:

 var Circle = function(radius) {
        this.radius = radius;

        asCircle.call(this);
    };

我是否不太理解 call() 在被调用后如何持续存在?

这两个片段在继承方面会有什么区别吗?:

function Animal(name){
   this.name = name;
    this.speak = function(){ 
       console.log("my name is: " + this.name);
    }
};
function Cat(name) {
    this.catproperty = "whatever";
    Animal.call(this, name);
}
Cat.prototype = new Animal();

var cat = new Cat('Joe');
cat.speak();

对比:

function Animal(name){
    this.name = name;
    this.speak = function(){ 
       console.log("my name is: " + this.name);
    }
};

function Cat(name) {
 this.name = name;
 this.catproperty = "whatever";
}

Animal.call(Cat.prototype, );

var cat = new Cat('Joe');
cat.speak();

最佳答案

I thought that call() assigned this scope in the same moment it is invoqued, and only in that moment.

它为该函数调用设置 this 的值。

asCircle 函数修改 this 引用的对象

函数运行结束后,this 的值消失。值的更改不会消失。

关于javascript - 使用 call() 进行继承。为什么它会持续存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49626528/

相关文章:

javascript - JavaScript 中的对象继承

javascript - 如何从 javascript 类型中删除方法

javascript - 我可以在 JavaScript 的原型(prototype)函数中使用私有(private)方法吗?

javascript - 检索jquery附加的div

javascript - LaTex 数学到 ASCIImath 的转换

javascript - IOS 的 Api phonegap 3.3.0 相机无法正常工作

javascript - 比较 2 列表得到移动 id + 偏移量 + 方向

javascript - 为什么除了 `goog.base(this)` 之外还需要 `goog.inherits()` ?

Javascript 找到原型(prototype)链的开始