我是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中使用吗?
(对不起!如果问题存在。)
答案 0 :(得分:7)
我想知道以下语法是否正确?
cat c = new animal;
不,JavaScript变量总是松散地输入,因此您不会为它们声明类型,只需使用var
(以及ES6,let
)声明它们。
所以:
var c = new animal;
附注#1:在JavaScript中,压倒性的约定是使用初始大写字母表示用作构造函数的函数(例如,通过new
关键字)。例如,Animal
和Cat
,而不是animal
和cat
。
附注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函数,它创建一个具有特定底层原型的对象。正确的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
作为其原型。
完整示例:
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");
答案 1 :(得分:3)
不,不是。在JavaScript中,您无法声明变量的类型。变量的类型是其当前值的类型,因此
var c = new animal(); //correct
但
cat c = new animal(); //parse error.