<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
</style>
</head>
<body>
<script>
function Animal(){}
function Dog (age){
this.name = 'fuck you' ;
this.age = age
}
var dog = new Dog(12);
console.log(dog);
Dog.prototype = Animal;
var dog2 = new Dog(12);
console.log(dog2);
</script>
</body>
</html>
1.输出分别为Dog{age:12,name:'fuck you'} Dog{age:12},
为什么添加Dog.prototype = Animal 后结果不一样? 求原理解释?
Animal
是 constructor
, Animal.prototype
才是原型。
看你的意思,应该是想 Dog.prototype = new Animal();
不过关于继承,比较麻烦,来看看 TypeScript 是怎么翻译的吧
typescript
class Animal {}
class Dog extends Animal {
name;
age;
constructor(age) {
super();
this.name = "fuck you";
this.age = age;
}
}
翻译成 javascript
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Animal = (function () {
function Animal() {
}
return Animal;
}());
var Dog = (function (_super) {
__extends(Dog, _super);
function Dog(age) {
_super.call(this);
this.name = "fuck you";
this.age = age;
}
return Dog;
}(Animal));
当为一个对象属性赋值是要遵循以下规则:
当对象的原型链中的原型对象上有对应的属性名,但是其是只读的,那么对象属性的赋值操作无效
当对象的原型链中的原型对象上有对应的属性名,但是其是可写的,且设置了set方法,那么对象属性的赋值操作无效,转而调用调用原型对象中的属性的set方法
当对象的原型链中的原型对象上有没有对应的属性名,那么直接在当前对象上添加这个属性(如果没有这个属性)并赋值
还有一个函数对象其有一个name属性,并且这个属性是只读的,
问题呈现出所所述的结果,原因就源于此~~
function Animal(){}
function Dog (age){
this.name = 'fuck you' ;
this.age = age
}
var dog = new Dog(12);
console.log(dog);
Dog.prototype = Animal;//将一个函数对象作为Dog的原型对象,其带有一个name只读属性
var dog2 = new Dog(12);
console.log(dog2);