代码块一
$(function() {
function Dog(){
}
var d = new Dog();
console.log(d.__proto__);
console.log(Dog.prototype);
}
可以发现d.__proto__和Dog.prototype指向的是同一个原型对象
一个对象由一个函数实例化出来,则该对象和该函数指向的是同一个原型对象
- 示例图
代码块二
自定义一个原型对象
$(function() {
function Dog(){
}
Dog.prototype = {
constructor:Dog,
init:function () {
this.name = 'wc';
this.age = 1;
},
say:function(){
console.log(this.name,this.age); //wc 1
}
}
var d = new Dog();
d.init();
d.say();
如何在不调用init()的情况下也能够使用name和age
$(function() {
function Dog(){
return new Dog.prototype.init();
}
Dog.prototype = {
constructor:Dog,
init:function () {
this.name = 'wc';
this.age = 1;
},
say:function(){
console.log(this.name,this.age);
}
}
var d = new Dog();
d.say();
}
报错: d.say is not a function TypeError: d.say is not a function 原因如下
解决办法:把init函数的原型对象改为Dog函数的原型对象。
最终版
$(function() {
function Dog(){
return new Dog.prototype.init();
}
Dog.prototype = {
constructor:Dog,
init:function () {
this.name = 'wc';
this.age = 1;
},
say:function(){
console.log(this.name,this.age);
}
}
Dog.prototype.init.prototype = Dog.prototype;
window.Player = Player;
var d = new Dog();;
d.say();
}