javascript - 原型(prototype)实例如 cat c = new Animal();?

标签 javascript jquery oop prototype

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

function animal(){
  // some bse code
}


function cat(){
  //some cat code
}

// I know this syntax and works well
cat.prototype= new animal;

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

cat c = new animal;

在 JavaScript 中可以吗?

(抱歉!如果问题存在。)

最佳答案

and I would like to know the below syntax is correct?

cat c = new animal;

不,JavaScript 变量始终是松散类型的,因此您无需为它们声明类型,只需使用 var 声明它们即可。 (在 ES6 中, let )。

所以:

var c = new animal;
<小时/>

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

<小时/>

旁注 #2:关于此:

// I know this syntax and works well
cat.prototype= new animal;

这是一种常见但糟糕的做法。以下是正确执行此操作的方法:

cat.prototype = Object.create(animal.prototype);
cat.prototype.constructor = cat;

...然后在 cat ,作为第一件事:

animal.call(this);

更新大小写的完整示例:

function Animal() {
}

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

    // ...add Cat-level initialization here
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;
<小时/>

关于Object.create :这是一个 ES5 函数,用于创建具有特定底层原型(prototype)的对象。正确的 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();
    };
}
<小时/>

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

function Animal(age) {
    this.age = age;
}

我们会为 age 付出什么?在 Cat.prototype = new Animal(???);线?

回答:我们不这样做。我们不应该打电话 Animal ,这是实例的构造函数,直到我们构造一个实例。相反,我们为Cat.prototype创建一个新对象。属性,并赋予该新对象 Animal.prototype作为其原型(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");

关于javascript - 原型(prototype)实例如 cat c = new Animal();?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22478896/

相关文章:

javascript - Pasting Image to <div> 多次粘贴一个小图像以适应 Div

javascript - 我需要使用 Galleria 模块旋转(滚动)图像

javascript - 单击某个项目时停止执行代码

java - 为什么 Java 方法需要返回类型

java - 静态方法如何返回不同的实现类?

python - 定义要在子类的子集中使用的属性

javascript - 切换在 jQuery 中不起作用

javascript - 我的 json 请求不会触发 beforeSend 请求。似乎无法弄清楚为什么

javascript - 用 grunt 替换变量

javascript - 如何将日期选择器设置为 fiddle 中的文本框?