Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.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中工作?_Javascript - Fatal编程技术网

原型如何在javascript中工作?

原型如何在javascript中工作?,javascript,Javascript,我知道已经有问题了,但我必须说清楚 function Animal(species) { this.species = species; } Animal.prototype.getSpecies = function() { return "Animal is " + this.species; }; (function() { var animal1 = new Animal("Snake"); var animal2 = new Animal("Wolf

我知道已经有问题了,但我必须说清楚

function Animal(species) {
    this.species = species;
}
Animal.prototype.getSpecies = function() {
    return "Animal is " + this.species;
};


(function() {
    var animal1 = new Animal("Snake");
    var animal2 = new Animal("Wolf");
    var animal3 = new Animal("Tiger");
}());
这就是我的理解。

函数/方法getSpecies()在prototype对象中的所有动物对象之间共享。 我理解对了吗

\u Proto\u
是指向原型对象的指针是否正确


谢谢你的帮助。

是的,你是对的,这就是它的工作原理
\uuuuuuu proto\uuuuuuuuu
不是一个指针,它是一个参考,它的使用是无润滑的。在Javascript中,实际指针不存在,但引用存在

如果您创建的类型继承自以下动物:

function FastAnimal () {
    Animal.call(this, 'extreme-fast');
}

FastAnimal.prototype = Object.create(Animal.prototype);
FastAnimal.prototype.constructor = FastAnimal;
FastAnimal.prototype.getSpeed = function () { return '1MILLION'; };


var fa = new FastAnimal();


fa.getName = function () {}
fa
中的属性或方法的查找将按此方式进行:

  • fa
    是否有自己的属性(如getName)
  • 它是否存在于
    FastAnimal.prototype
    (getSpeed)中
  • 它是否存在于
    动物中
  • 一般来说:只要有
    prototype
    s在路上,这种查找就会继续进行。然而,这就是引擎盖下发生的事情,被称为原型链

    注意:

    如果要循环给定对象的属性,有两种方法:

    for (var prop in obj) {
        //do stuff
    }
    
    这包括原型的属性,通常不是人们想要的,这就是为什么

    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            //do stuff
        }
    }
    
    是一种常见的模式,但是有一种新型的循环即将出现,希望在不久的将来可以使用

    for (var prop of obj) {}
    
    这也明确排除了对象原型的属性

    是的,你说得对 如果你使用 animal1.getSpecies==animal2.getSpecies true

    anima2.getSpecies==animal3.getSpecies true


    只有一份功能和原型副本存在

    是----------------线的点是什么:FastAnimal.prototype.constructor=FastAnimal?这是一种修复…对象。创建(…)将所有属性从Animals原型复制到FastAnimals one,其中包括构造函数,因此您需要修复它。
    for(var prop of obj){}
    是ES6,例如Internet Explorer不支持。MDN将其标记为实验技术。不要在生产中使用。正如你已经说过的,这就是我为什么写“希望在不久的将来可用”«…是的,更新了我的评论,但真正的目的是发布对ES6的引用。