gpt4 book ai didi

javascript - OOP Javascript 与对象字面量

转载 作者:行者123 更新时间:2023-12-03 09:37:38 25 4
gpt4 key购买 nike

我发现自己很少会使用OOP,我的意思是这样

function Person(name){
return this.name = name;
}

Person.prototype.dateOfBirth = function(){
//some stuff here
}

var John = new Person('John');
console.log(John.dateOfBirth);

也许我没有构建框架或其他什么,但有时我喜欢使用对象文字来分组我的方法,例如

    var John = {
name:'John',
dateOfBirth: function(){
// return etc
}
}

John.dateOfBirth();

也许因为 JS 是客户端语言,所以 OOP 相当多余,你们能分享一下使用 JS 的 OOP 经验吗?我学习了 JS 的基本知识,如原型(prototype)继承和高级对象,但我还没有找到它的任何用例。

最佳答案

查看暴露模块模式,您可以控制暴露的内容和不暴露的内容。我认为它提供了人们在 OOP 中所希望的公共(public)/隐私控制。

This blog post is a good example

var Person = (function() {

var name = "default";

function dateOfBirth() {
privateBirthCalculation(); //can only be invoked inside of the scope
console.log( 'dateOfBirth' );
}

function privateBirthCalculation() {
console.log( 'my private method' );
}

// explicitly return public methods and properties when this object is instantiated
return {
dateOfBirth : dateOfBirth,
name: name
};

})();

关于javascript - OOP Javascript 与对象字面量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31283310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com