javascript – 不是功能?

当我运行以下代码时,我被告知,该谈话不是一个功能.
为什么?
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

他谈到在大约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

以及相关的引用:

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现在是真的.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...