当我运行以下代码时,我被告知,该谈话不是一个功能.
为什么?
为什么?
function cat(name) { talk = function() { alert(" say meeow!" ) } } cat("felix"); cat.talk()
解决方法
你要做的是创建一个函数是构造函数的对象,但代码实际上做的是将变量talk设置为函数.你要:
function cat(name) { this.talk = function() { alert(" say meeow!" ) } } var myCat = new cat("felix"); myCat.talk()
编辑:
相关的javascript技术讲座:http://www.youtube.com/watch?v=ljNi8nS5TtQ
function Circle(radius){ this.radius = radius; this.area = function(){ return this.radius * this.radius * Math.PI; }; } var instance = {}; Circle.call(instance,5); instance.area(); // ==> 78.5398 var instance2 = new Circle(5); instance2.area() // ==> 78.5398 instance instanceof Circle // ==> false instance2 instanceof Circle // ==> true
以及相关的引用:
The new keyword is just a shorthand that is saying “make a new object
and call the constructor on it … the new keyword has no other
meaning”
换句话说,他说当使用new关键字时,你将变量定义为一个对象,并在该对象的上下文中调用该函数(这指向你的对象).
new关键字所做的额外事情是将新制作的对象的原型设置为构造函数的原型.所以如果我们这样做:
function Circle(radius){ this.radius = radius; this.area = function(){ return this.radius * this.radius * Math.PI; }; } var instance = {}; Circle.call(instance,5); instance.__proto__ = Circle.prototype; // we set the prototype of the new object to that of the constructor instance.area(); // ==> 78.5398 var instance2 = new Circle(5); instance2.area() // ==> 78.5398 instance instanceof Circle // ==> true // this is now true instance2 instanceof Circle // ==> true
实例instanceof Circle现在是真的.