先看看代码:
function Queue() {
this.items = [];
//使用动态原型模式创建对象
if (typeof Queue.prototype.enqueue != 'function') {
//入队
Queue.prototype.enqueue = function () {
var len = arguments.length;
if (len == 0) {
return;
}
for (var i = 0; i < len; i++) {
this.items.push(arguments[i])
}
}
//出队,如果队列为空则返回false,否则则返回出队的元素
Queue.prototype.dequeue=function () {
var result = this.items.shift();
return typeof result != 'undefined' ? result : false;
}
//返回队首元素
Queue.prototype.front=function () {
return this.items[items.length - 1];
}
//队列是否为空
Queue.prototype.isEmpty=function () {
return this.items.length == 0;
}
//返回队列长度
Queue.prototype.size=function () {
return this.items.length;
}
//清空队列
Queue.prototype.clear=function () {
this.items = [];
}
//返回队列
Queue.prototype.show=function () {
return this.items;
}
}
}
//继承父类原型
function inheritPrototype(superTyep, subType) {
//创建寄生式继承
function inherit(p){
if(p==null) throw TypeError();//首先判断输入的参数是不是为空,为空则抛出异常
if(Object.create){ //判断当前浏览器支不支持Object.create方法,不支持则手写
return Object.create(p);
}
var t=typeof p;//进一步检测
if(t!=='object' && t!=='function'){
throw TypeError();
}
function f(){}//定义一个空构造函数
f.prototype=p;//将其原型属性设置为p
return new f();//使用f()创建p的继承对象
}
var prototype = inherit(superTyep.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
//利用寄生组合式继承队列类型
function priorityQueue() {
//继承父类的实例属性
Queue.call(this);
//初始化父类原型
new Queue();
//继承父类原型
inheritPrototype(Queue, priorityQueue);
console.log(priorityQueue.prototype.isEmpty) // 备注①
}
var ss=new priorityQueue();
ss.isEmpty();//备注②
在备注①里面,我得到这样一段代码:
function () {
return this.items.length == 0;
}
这说明通过priorityQueue的prototype里面可以获取到Queue的Prototype方法,
但是在备注②里面,我却得到了这样的错误提示:
Uncaught TypeError: ss.isEmpty is not a function
我想知道为什么新建的对象ss无法找到isEmpty这个方法。