原型实例如cat c = new animal();?

use*_*809 0 javascript oop jquery prototype

我是Javascript的新手,最近,我遇到了这个问题,我很想知道答案.

function animal(){
  // some bse code
}


function cat(){
  //some cat code
}

// I know this syntax and works well
cat.prototype= new animal;
Run Code Online (Sandbox Code Playgroud)

我想知道下面的语法是否正确?

cat c = new animal;
Run Code Online (Sandbox Code Playgroud)

在javascript中有可能吗?

(对不起!如果问题存在.)

T.J*_*der 7

我想知道下面的语法是否正确?

cat c = new animal;

不,JavaScript变量总是松散类型,所以你不要为它们声明类型,只需用var(和ES6中let)声明它们.

所以:

var c = new animal;
Run Code Online (Sandbox Code Playgroud)

旁注#1:在JavaScript中,压倒性的约定是使用初始大写字母表示用作构造函数的函数(例如,通过new关键字).例如,AnimalCat不是animalcat.


附注2:关于这个:

// I know this syntax and works well
cat.prototype= new animal;
Run Code Online (Sandbox Code Playgroud)

这是一种常见但很差的做法.以下是如何正确执行此操作:

cat.prototype = Object.create(animal.prototype);
cat.prototype.constructor = cat;
Run Code Online (Sandbox Code Playgroud)

......然后在cat第一件事中:

animal.call(this);
Run Code Online (Sandbox Code Playgroud)

更新大写的完整示例:

function Animal() {
}

function Cat() {
    Animal.call(this);

    // ...add Cat-level initialization here
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;
Run Code Online (Sandbox Code Playgroud)

关于Object.create:这是一个ES5函数,它使用特定的底层原型创建一个对象.正确的ES5版本有两个参数,它对第二个参数的作用不能在旧浏览器上填充.但是对于我们正在做的事情,我们只需要第一个参数,它可以在旧浏览器上填充:

if (!Object.create) {
    Object.create = function(proto, props) {
        if (typeof props !== "undefined") {
            throw "Object.create shims cannot implement the second argument.";
        }

        function ctor() { }
        ctor.prototype = proto;

        return new ctor();
    };
}
Run Code Online (Sandbox Code Playgroud)

那为什么Cat.prototype = new Animal;不好的做法呢?那么,如果Animal需要每个实例参数呢?考虑:

function Animal(age) {
    this.age = age;
}
Run Code Online (Sandbox Code Playgroud)

什么将我们给出ageCat.prototype = new Animal(???);行?

答:我们没有.在构造实例之前,我们不应该调用 Animal实例的构造函数.相反,我们为Cat.prototype属性创建一个新对象,并将该新对象Animal.prototype作为其原型.

完整的例子:

function Animal(age) {
    this.age = age;
}
function Cat(age, color) {
    Animal.call(this, age);
    this.color = color;
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

var c = new Cat(14, "Tabby");
Run Code Online (Sandbox Code Playgroud)