微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/js/152440.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐