dub*_*ech 6 javascript function
当我运行以下代码时,我被告知,该谈话不是一个功能.为什么?
function cat(name) {
talk = function() {
alert(" say meeow!" )
}
}
cat("felix");
cat.talk()
Run Code Online (Sandbox Code Playgroud)
你要做的是创建一个函数是构造函数的对象,但代码实际上做的是将变量设置talk为函数.你要:
function cat(name) {
this.talk = function() {
alert(" say meeow!" )
}
}
var myCat = new cat("felix");
myCat.talk()
Run Code Online (Sandbox Code Playgroud)
编辑:
相关的javascript技术讲座:http://www.youtube.com/watch?v = ljNi8nS5TtQ
他谈到在大约30分钟内构建具有函数的对象.他发布的代码是:
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
Run Code Online (Sandbox Code Playgroud)
以及相关的引用:
new关键字只是一个简写,就是说"创建一个新对象并在其上调用构造函数......新关键字没有其他含义"
换句话说,他说当使用new关键字时,你将变量定义为一个对象,并在该对象的上下文中调用该函数(this指向你的对象).
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
Run Code Online (Sandbox Code Playgroud)
instance instanceof Circle 现在是真的.