js构造函数

代码片段1

function Foo() {
    var bla = 1;
    return {
        foo:function(){
            return bla;
        }
    }
}

Foo.prototype.test = function() {
    console.log('abc');
};

var test = new Foo();
console.log(test.test)

如此为何不能访问到原型中的方法了,构造函数返回值应当怎么写才能把原型方法返回出来







代码片段2

  function Foo(age) {
        this.age = age;
        var bla = 1;
        return {
            
            foo:function(){
                return bla;
            },
            test:function(){
                Foo.prototype.test.apply(this,arguments);
            }
        }
    }

    Foo.prototype={
        constructor:Foo,
        test:function(){
            console.log(this);//指向object对象,下面有两个函数foo和test
            //console.log(this.age);
        }
    };

    var test = new Foo(23);
    test.test();
    也就是说new出来的对象已经不是指向原来构造函数,而是指向了object
阅读 3.8k
7 个回答

兄弟,构造函数不是那样用的

function Foo() {
    
}

Foo.prototype.test = function() {
    console.log('abc');
};

var test = new Foo();
console.log(test.test())

这样就行了

因为你构造函数返回的是一个对象,那么你new出来的对象就是你返回的那个对象,所以你在构造器的prototype上定义的函数,返回对象时访问不了的。

引用一句MDN上的定义:链接描述

如果构造函数返回了一个“对象”,那么这个对象会取代整个new出来的结果。

//所以:var test = new Foo();test是:
{
    foo:function(){
        return bla;
    }
}

而非你想要的Foo的实例。

你这个很简单,因为如果构造函数有返回值,那么不管是直接调用还是使用new操作符调用,都会返回其返回值所返回的内容,也就是你return后面跟的对象,那第一个问题就解决了,顺理成章第二个问题也是同样的,另外我需要告诉你,函数只是一个可执行的代码块,在运行的时候才绑定this以及其它作用域,所以第二个代码块里面,你通过第一个函数返回了带有foo和test的方法的对象,再用这个对象去调用一个函数(不管函数在哪儿,它只是一块代码),这个时候动态绑定this到这个对象上,所以this就是指向该对象本身,输出的当然不就是带有foo和test的对象吗。一般构造函数返回一个对象,是用在内部创建了一个对象并对其进行了相应操作再返回,是JavaScript设计模式的一种,但是一般情况下并不受到推崇,至少我个人这么认为。

试试这样:

function Foo() { 
    this.bla = 1; 
    this.foo = function(){ 
        return this.bla; 
    } ;
} 

构造函数写法有问题,不需要显式地返回对象,把需要的属性或方法挂在到this上就好了,new Foo()的过程会自动帮你创建空对象,初始化赋值并返回的。

function Foo(){
    var bla = 1
    this.foo = function(){
        return bla
    }
}
Foo.prototype.test = function() {
    console.log('abc')
}

var test = new Foo()
test.test() //'abc'
console.log(test.foo()) //1
console.log(test instanceof Foo); //false
console.log(test.constructor);  //Object

new Foo();应该将foo()复制给了变量test。

function Foo() {
    var bla = 1;
    this.foo = function(){
            return bla;
    }
}

Foo.prototype.test = function() {
    console.log('abc');
};

var test = new Foo();
console.log(test.test());
var Foo = (function(){
    var bla = 1;
    function foo(){
        return bla;
    }

    return foo;
})();
Foo.prototype.test = function(){
    console.log("abc");
};
var test = new Foo();
console.log(test.test());
var Foo = (function(){
    var bla = 1;
    function foo(){
        return bla;
    }
    foo.prototype = {
        constructor:foo,
        test:function(){
            alert("abc");
        }
    };
    return foo;
})();
var test = new Foo();
console.log(test.test());
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题