简体   繁体   English

如何提醒Shape,TwoDShape类的名称?

[英]How can I alert name of the class Shape,TwoDShape?

I have this Demo which execution alert and it is work well: 我有这个演示哪个执行警报,它工作得很好:

below the code. 代码下方。

var Shape = function(){};
var TwoDShape = function(){};
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){return this.name;};

alert('there is alert');​

when I add this line : extend(TwoDShape, Shape); 当我添加此行时: extend(TwoDShape, Shape);

I can't to execution alert as you can see Demo 我无法执行提醒,因为您可以看到演示

after this I add lines: 在此之后,我添加以下行:

var my = new TwoDShape();
alert(my.toString());
alert(TwoDShape.prototype.name);
alert(my.hasOwnProperty('name'));

to alert the name of the class shape or TwoDShape but I can't successfull to display the class.name why ? 提醒类shapeTwoDShape的名称,但我无法成功显示class.name为什么?

here is the full code: 这是完整的代码:

First, you do not have function extend() inside you code, so the code encounters error there and stopped running. 首先,代码中没有函数extend() ,因此代码在那里遇到错误并停止运行。

So I fixed it using jQuery $.extend() , or you can write the extend() yourself (see Jimmy's answer). 因此,我使用jQuery $.extend()对其进行$.extend() ,或者您可以自己编写extend() (请参阅吉米的答案)。

Secondly, if you want all Shape/TwoDShape instances have the class name to be accessible using toString() , you need to extend the prototype: 其次,如果希望所有Shape / TwoDShape实例都具有可使用toString()访问的类name ,则需要扩展原型:

TwoDShape.prototype = $.extend(TwoDShape.prototype, Shape.prototype);

See the jsfiddle I created http://jsfiddle.net/4Bjjp/6/ on extending prototype 参见我在扩展原型上创建的jsfiddle http://jsfiddle.net/4Bjjp/6/

Your code break because extend function does not exist. 您的代码中断,因为extend功能不存在。 You've to implement your own to make it work. 您必须实现自己的才能使其工作。 Here is a simple implementation. 这是一个简单的实现。

function extend(destination, source) {
  for (var key in source) {
    if(source.hasOwnProperty(key)) {
      destination[key] = source[key];
    }
  }

  return destination;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM